Can I reuse maven credentials for multiple maven repositories?

We are having a couple of internal repositories which are password protected. They all have the same readonly username/password so I wanted to reuse it but when I extract method I get weird “closure” exceptions (not a Groovy expert).

maven {
       credentials {
         username archiva_username
         password archiva_password
       }
       url "http://archiva.abc.com/archiva/repository/public/"
     }
     maven {
       credentials {
         username archiva_username
         password archiva_password
       }
       url "http://archiva.abc.com/archiva/repository/fallback/"
     }
     ...

which I wanted to replace with

maven {
       credentials getArchiva()
       url "http://archiva.abc.com/archiva/repository/public/"
     }
     maven {
       credentials getArchiva()
       url "http://archiva.abc.com/archiva/repository/fallback/"
     }
     ...
     private Object getArchiva() {
       credentials {
        username archiva_username
        password archiva_password
      }
    }

But then I get

> Could not find method getArchiva() for arguments [] on org.gradle.api.internal.artifacts.repositories.DefaultMavenArtifactRepository_Decorated@252c65db.

I’m aware that the “builder” is missing context here but I lack some Groovy/Gradle knowledge to make it work.

I am not 100% sure but does this work for you?

def archivaCredentials = {
    credentials {
       username archiva_username
       password archiva_password
    }
}
  maven(url: "http://archiva.abc.com/archiva/repository/public/", credentials: archivaCredentials)
maven(url: "http://archiva.abc.com/archiva/repository/fallback/", credentials: archivaCredentials)

Nope that did not work. I still get something like

Could not find method maven() for arguments

[{url=http://archiva.abc.com/archiva/repository/external_free/, credentials=build_d41b71eu3715lg4l7sqmsbsat$_run_closure1_closure5_closure12@fd7ec14} ] on repository container.

But I managed to do it like this based on Closure tutorial of Groovy. Still… I need to get more into closures because I did not get it to work for credentials though.

def companyMaven = { url ->
      maven {
        credentials {
          username archiva_username
          password archiva_password
        }
        url url
      }
    }
  companyMaven("http://archiva.abc.com/archiva/repository/external_free/")

Pretty cool stuff though.