---
# System prepended metadata

title: Query 249

---

To manage the encryption of Amazon Elastic Block Store (EBS) volumes using the AWS Key Management Service (KMS) in Python, you can use the AWS SDK for Python (Boto3). Below is a Python script that demonstrates how to create an encrypted EBS volume, attach it to an EC2 instance, and detach it. This script assumes that you have already created a KMS key that you want to use for encryption.

Make sure you have the Boto3 library installed, and configure your AWS credentials using aws configure before running the script.
```
import boto3

# Specify your AWS region and KMS key ID
region = 'us-east-1'  # Change to your desired region
kms_key_id = 'your-kms-key-id'  # Replace with your KMS key ID

# Initialize the AWS clients
ec2 = boto3.client('ec2', region_name=region)
kms = boto3.client('kms', region_name=region)

def create_encrypted_ebs_volume(volume_size_gb, instance_id):
    # Create an encrypted EBS volume
    response = ec2.create_volume(
        AvailabilityZone=region + 'a',  # Change to your desired availability zone
        Encrypted=True,
        KmsKeyId=kms_key_id,
        Size=volume_size_gb,
    )
    volume_id = response['VolumeId']
    print(f"Created encrypted EBS volume with ID: {volume_id}")

    # Attach the EBS volume to the specified EC2 instance
    ec2.attach_volume(
        Device='/dev/sdf',  # Change to your desired device name
        InstanceId=instance_id,
        VolumeId=volume_id
    )
    print(f"Attached EBS volume {volume_id} to EC2 instance {instance_id}")

def detach_ebs_volume(volume_id, instance_id):
    # Detach the EBS volume from the EC2 instance
    ec2.detach_volume(
        InstanceId=instance_id,
        VolumeId=volume_id
    )
    print(f"Detached EBS volume {volume_id} from EC2 instance {instance_id}")

    # Delete the EBS volume (optional)
    ec2.delete_volume(VolumeId=volume_id)
    print(f"Deleted EBS volume {volume_id}")

# Example usage:
instance_id = 'your-ec2-instance-id'  # Replace with your EC2 instance ID
volume_size_gb = 10  # Specify the size of the EBS volume in GB

# Create an encrypted EBS volume and attach it to the EC2 instance
create_encrypted_ebs_volume(volume_size_gb, instance_id)

# Perform other tasks...

# Detach and optionally delete the EBS volume
# detach_ebs_volume('your-ebs-volume-id', instance_id)
```
This script creates an encrypted EBS volume, attaches it to an EC2 instance, and demonstrates how to detach and optionally delete the volume. You can customize the device name, availability zone, and other parameters as needed for your use case.