Custom taks for Maven publishing

I’m trying to write custom task inside plugin (reusing maven-publish plugin), which will do publishing to S3 bucket.
But I have problem with dynamically adding repositories to current publish repositories.

I’m using down listed code, and I’m getting this error:
‘Cannot configure the ‘publishing’ extension after it has been accessed.’

I found couple post related to subject, but still it’s not to clear for me how to go around this problem?
Does someone have some advice, how to solve this or maybe how to take another approach?

    public void publishToS3() {

        getProject().plugins.withType(MavenPublishPlugin) {
            getProject().extensions.configure PublishingExtension, new ClosureBackedAction( {
                repositories {
                    maven {
                        url "s3://" + awsS3BucketName
                        credentials(AwsCredentials) {
                            accessKey awsAccessKey
                            secretKey awsSecretKey


This shouldn’t be done inside a task action. The actual publishing is done by tasks which are created by the ‘maven-publish’ plugin whenever you configure a publication and repository. All you need to do is configure the publication and repository in your plugin.