QGIS – Adding Cloud-Optimized GeoTIFFs from AWS S3 to QGIS Map Canvas Programmatically

amazon s3cloud-optimized-geotiffpyqgis-3qgis-3

I have a private bucket in S3 with COGs in it.
Following the instructions here, it's actually very simple to do it manually.
However, this does indeed only work manually.
Trying to add a COG with the usual iface.addRasterLayer() dialogue works perfectly fine when my S3 bucket, or any other online host is public read, unfortunately, my bucket isn't and can't be public.

So the question is, How do I perform the manual add raster layer -> Protocol -> AWS S3 dialog programmatically with python?
enter image description here

Best Answer

You can add S3 using the following

bucket_name = 'your_bucket_name'
bucket_path_to_tif = 'subdir/myfile.tif'

rlayer = QgsRasterLayer(f'/vsis3/{bucket_name}/{bucket_path_to_tif}', "My layer name")
QgsProject.instance().addMapLayer(rlayer)

You can get the uri provided to rlayer using below command from an existing s3 layer added through the GUI

iface.activeLayer().dataProvider().dataSourceUri()

It's also visible by going to the S3 layer "Properties" panel and in the tab "Information" you will see a line with

Dataset Description /vsis3/your_bucket_name/subdir/myfile.tif

The syntax is borrowed from gdal vsis3 driver it seems e.g https://gdal.org/user/virtual_file_systems.html#vsis3-aws-s3-files

Related Question