<commit_before>#!/usr/bin/python
#

# (c) 2015, <NAME> <<EMAIL>>
#
# This file is part of Ansible
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software.  If not, see <http://www.gnu.org/licenses/>.

######################################################################

DOCUMENTATION = '''
---
module: docker_login
author: <NAME>
version_added: "2.0"
short_description: Manage Docker registry logins
description:
     - Ansible version of the "docker login" CLI command.
     - This module allows you to login to a Docker registry without directly pulling an image or performing any other actions.
     - It will write your login credentials to your local .dockercfg file that is compatible to the Docker CLI client as well as docker-py and all other Docker related modules that are based on docker-py.
options:
  registry:
    description:
       - URL of the registry, defaults to: https://index.docker.io/v1/
    required: false
    default: https://index.docker.io/v1/
  username:
    description:
       - The username for the registry account
    required: true
  password:
    description:
       - The plaintext password for the registry account
    required: true
  email:
    description:
       - The email address for the registry account. Note that private registries usually don't need this, but if you want to log into your Docker Hub account (default behaviour) you need to specify this in order to be able to log in.
    required: false
    default: None
  reauth:
    description:
       - Whether refresh existing authentication on the Docker server (boolean)
    required: false
    default: false
  dockercfg_path:
    description:
       - Use a custom path for the .dockercfg file
    required: false
    default: ~/.docker/config.json
  docker_url:
    descriptions:
       - Refers to the protocol+hostname+port where the Docker server is hosted
    required: false
    default: unix://var/run/docker.sock
  timeout:
    description:
       - The HTTP request timeout in seconds
    required: false
    default: 600

requirements: [ "python >= 2.6", "docker-py" ]
'''

EXAMPLES = '''
Login to a Docker registry without performing any other action. Make sure that the user you are using is either in the docker group which owns the Docker socket or use sudo to perform login actions:

- name: login to DockerHub remote registry using your account
  docker_login:
    username: docker
    password: <PASSWORD>
    email: <EMAIL>

- name: login to private Docker remote registry and force reauthentification
  docker_login:
    registry: https://your.private.registry.io/v1/
    username: yourself
    password: <PASSWORD>
    reauth: yes

- name: login to DockerHub remote registry using a custom dockercfg file location
  docker_login:
    username: docker
    password: <PASSWORD>
    email: <EMAIL>
    dockercfg_path: /tmp/.mydockercfg

'''

import os.path
import json
import base64
from urlparse import urlparse

try:
    import docker.client
    from docker.errors import APIError as DockerAPIError
    has_lib_docker = True
except ImportError, e:
    has_lib_docker = False

try:
    from requests.exceptions import *
    has_lib_requests_execeptions = True
except ImportError, e:
    has_lib_requests_execeptions = False

class DockerLoginManager:

    def __init__(self, module):

        self.module = module
        self.registry = self.module.params.get('registry')
        self.username = self.module.params.get('username')
        self.password = self.module.params.get('password')
        self.email = self.module.params.get('email')
        self.reauth = self.module.params.get('reauth')
        self.dockercfg_path = os.path.expanduser(self.module.params.get('dockercfg_path'))

        docker_url = urlparse(module.params.get('docker_url'))
        self.client = docker.Client(base_url=docker_url.geturl(), timeout=module.params.get('timeout'))

        self.changed = False
        self.response = False
        self.log = list()

    def login(self):

        if self.reauth:
            self.log.append("Enforcing reauthentification")

        # Extract hostname part from self.registry if url was specified.
        registry_url = urlparse(self.registry)
        self.registry = registry_url.netloc or registry_url.path

        # Connect to registry and login if not already logged in or reauth is enforced.
        try:
            self.response = self.client.login(
                self.username,<commit_msg>Improve registry key parity between clients * Don't extract hostname part from docker_url since this leads to docker CLI client not recognizing Docker Hub credentials set by docker_login module anymore (looks for the full URL as a key).<commit_after>#!/usr/bin/python
#

# (c) 2015, <NAME> <<EMAIL>>
#
# This file is part of Ansible
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software.  If not, see <http://www.gnu.org/licenses/>.

######################################################################

DOCUMENTATION = '''
---
module: docker_login
author: <NAME>
version_added: "2.0"
short_description: Manage Docker registry logins
description:
     - Ansible version of the "docker login" CLI command.
     - This module allows you to login to a Docker registry without directly pulling an image or performing any other actions.
     - It will write your login credentials to your local .dockercfg file that is compatible to the Docker CLI client as well as docker-py and all other Docker related modules that are based on docker-py.
options:
  registry:
    description:
       - URL of the registry, defaults to: https://index.docker.io/v1/
    required: false
    default: https://index.docker.io/v1/
  username:
    description:
       - The username for the registry account
    required: true
  password:
    description:
       - The plaintext password for the registry account
    required: true
  email:
    description:
       - The email address for the registry account. Note that private registries usually don't need this, but if you want to log into your Docker Hub account (default behaviour) you need to specify this in order to be able to log in.
    required: false
    default: None
  reauth:
    description:
       - Whether refresh existing authentication on the Docker server (boolean)
    required: false
    default: false
  dockercfg_path:
    description:
       - Use a custom path for the .dockercfg file
    required: false
    default: ~/.docker/config.json
  docker_url:
    descriptions:
       - Refers to the protocol+hostname+port where the Docker server is hosted
    required: false
    default: unix://var/run/docker.sock
  timeout:
    description:
       - The HTTP request timeout in seconds
    required: false
    default: 600

requirements: [ "python >= 2.6", "docker-py" ]
'''

EXAMPLES = '''
Login to a Docker registry without performing any other action. Make sure that the user you are using is either in the docker group which owns the Docker socket or use sudo to perform login actions:

- name: login to DockerHub remote registry using your account
  docker_login:
    username: docker
    password: <PASSWORD>
    email: <EMAIL>

- name: login to private Docker remote registry and force reauthentification
  docker_login:
    registry: your.private.registry.io
    username: yourself
    password: <PASSWORD>
    reauth: yes

- name: login to DockerHub remote registry using a custom dockercfg file location
  docker_login:
    username: docker
    password: <PASSWORD>
    email: <EMAIL>
    dockercfg_path: /tmp/.mydockercfg

'''

import os.path
import json
import base64
from urlparse import urlparse

try:
    import docker.client
    from docker.errors import APIError as DockerAPIError
    has_lib_docker = True
except ImportError, e:
    has_lib_docker = False

try:
    from requests.exceptions import *
    has_lib_requests_execeptions = True
except ImportError, e:
    has_lib_requests_execeptions = False

class DockerLoginManager:

    def __init__(self, module):

        self.module = module
        self.registry = self.module.params.get('registry')
        self.username = self.module.params.get('username')
        self.password = <PASSWORD>('password')
        self.email = self.module.params.get('email')
        self.reauth = self.module.params.get('reauth')
        self.dockercfg_path = os.path.expanduser(self.module.params.get('dockercfg_path'))

        docker_url = urlparse(module.params.get('docker_url'))
        self.client = docker.Client(base_url=docker_url.geturl(), timeout=module.params.get('timeout'))

        self.changed = False
        self.response = False
        self.log = list()

    def login(self):

        if self.reauth:
            self.log.append("Enforcing reauthentification")

        # Connect to registry and login if not already logged in or reauth is enforced.
        try:
            self.response = self.client.login(
                self.username,
{'fraction_non_alphanumeric': 0.08739126087391261, 'fraction_numerical': 0.0032996700329967, 'mean_word_length': 3.236340533672173, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 26, 'https://': 5, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1559789', 'n_tokens_mistral': 2789, 'n_tokens_neox': 2631, 'n_words': 1074}