Observação:

Migrar Segredos do AWS Secrets Manager para o Oracle Cloud Infrastructure Secrets in Vault

Introdução

Benefícios ao migrar segredos do Amazon Web Services (AWS) para o OCI (Oracle Cloud Infrastructure):

Tipos de Segredos Suportados no OCI Vault

Objetivos

Pré-requisitos

Migre segredos da AWS para a OCI

  1. Recupere e exiba segredos da AWS. Para migrar segredos da AWS, primeiro certifique-se de ter uma lista dos segredos a serem transferidos. Neste exemplo, estamos migrando dois segredos: awssecret4 e awssecret5.

    Botão Editar

    A captura de tela a seguir mostra os segredos no AWS Secrets Manager antes da migração.

    Botão Editar

    Botão Editar

  2. Crie um vault e uma chave de criptografia no OCI. Para configurar um OCI Vault e uma chave para criptografar segredos, consulte Criando uma Chave de Criptografia Principal.

    Botão Editar

    Botão Editar

  3. Use o script Python para migrar segredos. Faça download do script Python a seguir e salve-o como aws_to_oci_secret_migration.py. O script automatiza o processo de recuperar segredos da AWS e armazená-los no OCI Vault.

    Observação: Substitua placeholders como your_aws_secret1, your_aws_region, your_oci_vault_id etc., pelos valores reais. O prefixo especificado será usado para criar os segredos no vault, ajudando a isolar a criação de segredos usando o 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. Depois que o script for salvo, execute-o com o comando a seguir.

    python3 aws_to_oci_secret_migration.py
    

    Botão Editar

  5. Após a execução bem-sucedida do script, você poderá verificar os segredos recém-criados no OCI Vault.

    Botão Editar

    Botão Editar

Próximas Etapas

A migração de segredos da AWS para a OCI pode ajudar a simplificar suas operações, especialmente se você estiver aproveitando a OCI para o resto da sua infraestrutura de nuvem. Usando a automação Python, você pode transferir segredos com eficiência, garantindo que eles sejam armazenados com segurança e estejam em conformidade com os padrões de criptografia da OCI.

Confirmações

Mais Recursos de Aprendizagem

Explore outros laboratórios em docs.oracle.com/learn ou acesse mais conteúdo de aprendizado gratuito no canal Oracle Learning YouTube. Além disso, visite education.oracle.com/learning-explorer para se tornar um Oracle Learning Explorer.

Para obter a documentação do produto, visite o Oracle Help Center.