pheonix
pheonix

Reputation: 73

how can I create docker private repository via docker hub api?

I can create public repository via docker hub api. How can I private repository?

url='http://index.docker.io/v1/repositories/(username)/(new_repo_name)/'
header = {'content-type': 'application/json','Accept': 'application/json','X-Docker-Token': 'true'}
data = [{"id": "1020903f808f"}]
auth=HTTPBasicAuth(username,password)
requests.put(url,headers=header, auth=auth,data=data)

and my image is:

(username)/(new_repo_name)       latest             1020903f808f 

Upvotes: 3

Views: 1854

Answers (2)

starfry
starfry

Reputation: 9983

With curl (useful from a shell script):

TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${USER}'", "password": "'${PASS}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)

curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/" \
 --data 'description=test' \
 --data 'full_description=full-description' \
 --data 'is_private=false' \
 --data 'name=test' \
 --data "namespace=${USER}"

Upvotes: 2

rickgn
rickgn

Reputation: 98

This is not documented anywhere, but by checking the requests in the browser I managed to get the below code to work. It requires a JWT token. A quick and dirty way to get yours is to login in with Chrome and copy-paste it from the debug view (ctrl+shift+i).

class DockerHub(object):
def __init__(self, url=None, version='v2', headers=None, jwt_token=None):
    self.version = version
    self.url = '{0}/{1}'.format(url or 'https://hub.docker.com', self.version)
    self.headers = headers or {}
    if jwt_token:
        self.headers['Authorization'] = 'JWT ' + jwt_token

def create_private_docker_hub_repo(self, reponame, orgname, jwt_token, summary=None, description=None):
    payload = {
        'description': summary or '',
        'full_description': description or '',
        'is_private': 'true',
        'name': reponame,
        'namespace': orgname
    }
    resp = requests.post(
        self.url + '/repositories/',
        data=payload,
        headers=self.headers,
    )
    return resp.json()

def set_group_permission_for_repo(self, repo, orgname, groupname, permission='read'):
    group_id = {it['name']: it['id'] for it in self.get_org_groups(orgname)}[groupname]
    if not permission in ('write', 'read'):
        raise Exception('permission must be write or read')
    resp = requests.post(
        'https://hub.docker.com/v2/repositories/{org}/{repo}/groups/'.format(
            org=orgname,
            repo=repo
        ),
        data={'group_id': group_id, 'permission': permission},
        headers=self.headers
    )
    return resp.json()

def get_org_groups(self, orgname):
    resp = requests.get(
        'https://hub.docker.com/v2/orgs/{org}/groups/?page_size=100'.format(org=orgname),
        headers=self.headers,
    )
    return resp.json()['results']

Upvotes: 4

Related Questions