def main():
    argument_spec = dict(name=dict(type='str', required=True), )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        min_docker_api_version='1.20',
    )

    try:
        container = client.get_container(client.module.params['name'])

        client.module.exit_json(
            changed=False,
            exists=(True if container else False),
            container=container,
        )
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e),
                    exception=traceback.format_exc())
    except RequestException as e:
        client.fail(
            'An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'
            .format(e),
            exception=traceback.format_exc())
def main():
    argument_spec = dict(name=dict(type='str', required=True),
                         state=dict(type='str',
                                    default='present',
                                    choices=['absent', 'present']),
                         data=dict(type='str', no_log=True),
                         data_is_b64=dict(type='bool', default=False),
                         labels=dict(type='dict'),
                         force=dict(type='bool', default=False))

    required_if = [('state', 'present', ['data'])]

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=required_if,
        min_docker_version='2.1.0',
        min_docker_api_version='1.25',
    )

    try:
        results = dict(changed=False, secret_id='')

        SecretManager(client, results)()
        client.module.exit_json(**results)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e),
                    exception=traceback.format_exc())
    except RequestException as e:
        client.fail(
            'An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'
            .format(e),
            exception=traceback.format_exc())
def main():
    argument_spec = dict(name=dict(type='list', elements='str'), )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        min_docker_api_version='1.20',
    )
    if client.module._name == 'docker_image_facts':
        client.module.deprecate(
            "The 'docker_image_facts' module has been renamed to 'docker_image_info'",
            version='2.12')

    try:
        results = dict(changed=False, images=[])

        ImageManager(client, results)
        client.module.exit_json(**results)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e),
                    exception=traceback.format_exc())
    except RequestException as e:
        client.fail(
            'An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'
            .format(e),
            exception=traceback.format_exc())
def main():
    argument_spec = dict(
        containers=dict(type='bool', default=False),
        containers_filters=dict(type='dict'),
        images=dict(type='bool', default=False),
        images_filters=dict(type='dict'),
        networks=dict(type='bool', default=False),
        networks_filters=dict(type='dict'),
        volumes=dict(type='bool', default=False),
        volumes_filters=dict(type='dict'),
        disk_usage=dict(type='bool', default=False),
        verbose_output=dict(type='bool', default=False),
    )

    option_minimal_versions = dict(
        network_filters=dict(docker_py_version='2.0.2'),
        disk_usage=dict(docker_py_version='2.2.0'),
    )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        min_docker_version='1.10.0',
        min_docker_api_version='1.21',
        option_minimal_versions=option_minimal_versions,
        fail_results=dict(can_talk_to_docker=False, ),
    )
    client.fail_results['can_talk_to_docker'] = True

    try:
        results = dict(changed=False, )

        DockerHostManager(client, results)
        client.module.exit_json(**results)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e),
                    exception=traceback.format_exc())
    except RequestException as e:
        client.fail(
            'An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'
            .format(e),
            exception=traceback.format_exc())
Ejemplo n.º 5
0
def main():
    argument_spec = dict(
        project_src=dict(type='path'),
        project_name=dict(type='str',),
        files=dict(type='list', elements='path'),
        state=dict(type='str', default='present', choices=['absent', 'present']),
        definition=dict(type='dict'),
        hostname_check=dict(type='bool', default=False),
        recreate=dict(type='str', default='smart', choices=['always', 'never', 'smart']),
        build=dict(type='bool', default=False),
        remove_images=dict(type='str', choices=['all', 'local']),
        remove_volumes=dict(type='bool', default=False),
        remove_orphans=dict(type='bool', default=False),
        stopped=dict(type='bool', default=False),
        restarted=dict(type='bool', default=False),
        scale=dict(type='dict'),
        services=dict(type='list', elements='str'),
        dependencies=dict(type='bool', default=True),
        pull=dict(type='bool', default=False),
        nocache=dict(type='bool', default=False),
        debug=dict(type='bool', default=False),
        timeout=dict(type='int', default=DEFAULT_TIMEOUT)
    )

    mutually_exclusive = [
        ('definition', 'project_src'),
        ('definition', 'files')
    ]

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        mutually_exclusive=mutually_exclusive,
        supports_check_mode=True,
        min_docker_api_version='1.20',
    )
    if client.module._name == 'docker_service':
        client.module.deprecate("The 'docker_service' module has been renamed to 'docker_compose'.", version='2.12')

    try:
        result = ContainerManager(client).exec_module()
        client.module.exit_json(**result)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc())
    except RequestException as e:
        client.fail('An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'.format(e), exception=traceback.format_exc())
Ejemplo n.º 6
0
def main():

    argument_spec = dict(
        registry_url=dict(type='str', default=DEFAULT_DOCKER_REGISTRY, aliases=['registry', 'url']),
        username=dict(type='str'),
        password=dict(type='str', no_log=True),
        email=dict(type='str', removed_in_version='2.14'),
        reauthorize=dict(type='bool', default=False, aliases=['reauth']),
        state=dict(type='str', default='present', choices=['present', 'absent']),
        config_path=dict(type='path', default='~/.docker/config.json', aliases=['dockercfg_path']),
    )

    required_if = [
        ('state', 'present', ['username', 'password']),
    ]

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=required_if,
        min_docker_api_version='1.20',
    )

    try:
        results = dict(
            changed=False,
            actions=[],
            login_result={}
        )

        manager = LoginManager(client, results)
        manager.run()

        if 'actions' in results:
            del results['actions']
        client.module.exit_json(**results)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc())
    except RequestException as e:
        client.fail('An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'.format(e), exception=traceback.format_exc())
def main():
    argument_spec = dict(volume_name=dict(type='str',
                                          required=True,
                                          aliases=['name']),
                         state=dict(type='str',
                                    default='present',
                                    choices=['present', 'absent']),
                         driver=dict(type='str', default='local'),
                         driver_options=dict(type='dict', default={}),
                         labels=dict(type='dict'),
                         force=dict(type='bool', removed_in_version='2.12'),
                         recreate=dict(
                             type='str',
                             default='never',
                             choices=['always', 'never', 'options-changed']),
                         debug=dict(type='bool', default=False))

    option_minimal_versions = dict(labels=dict(docker_py_version='1.10.0',
                                               docker_api_version='1.23'), )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        min_docker_version='1.10.0',
        min_docker_api_version='1.21',
        # "The docker server >= 1.9.0"
        option_minimal_versions=option_minimal_versions,
    )

    try:
        cm = DockerVolumeManager(client)
        client.module.exit_json(**cm.results)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e),
                    exception=traceback.format_exc())
    except RequestException as e:
        client.fail(
            'An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'
            .format(e),
            exception=traceback.format_exc())
def main():
    argument_spec = dict(
        source=dict(type='str', choices=['build', 'load', 'pull', 'local']),
        build=dict(type='dict', options=dict(
            cache_from=dict(type='list', elements='str'),
            container_limits=dict(type='dict', options=dict(
                memory=dict(type='int'),
                memswap=dict(type='int'),
                cpushares=dict(type='int'),
                cpusetcpus=dict(type='str'),
            )),
            dockerfile=dict(type='str'),
            http_timeout=dict(type='int'),
            network=dict(type='str'),
            nocache=dict(type='bool', default=False),
            path=dict(type='path', required=True),
            pull=dict(type='bool'),
            rm=dict(type='bool', default=True),
            args=dict(type='dict'),
            use_config_proxy=dict(type='bool'),
            target=dict(type='str'),
            etc_hosts=dict(type='dict'),
        )),
        archive_path=dict(type='path'),
        container_limits=dict(type='dict', options=dict(
            memory=dict(type='int'),
            memswap=dict(type='int'),
            cpushares=dict(type='int'),
            cpusetcpus=dict(type='str'),
        ), removed_in_version='2.12'),
        dockerfile=dict(type='str', removed_in_version='2.12'),
        force=dict(type='bool', removed_in_version='2.12'),
        force_source=dict(type='bool', default=False),
        force_absent=dict(type='bool', default=False),
        force_tag=dict(type='bool', default=False),
        http_timeout=dict(type='int', removed_in_version='2.12'),
        load_path=dict(type='path'),
        name=dict(type='str', required=True),
        nocache=dict(type='bool', default=False, removed_in_version='2.12'),
        path=dict(type='path', aliases=['build_path'], removed_in_version='2.12'),
        pull=dict(type='bool', removed_in_version='2.12'),
        push=dict(type='bool', default=False),
        repository=dict(type='str'),
        rm=dict(type='bool', default=True, removed_in_version='2.12'),
        state=dict(type='str', default='present', choices=['absent', 'present', 'build']),
        tag=dict(type='str', default='latest'),
        use_tls=dict(type='str', choices=['no', 'encrypt', 'verify'], removed_in_version='2.11'),
        buildargs=dict(type='dict', removed_in_version='2.12'),
    )

    required_if = [
        # ('state', 'present', ['source']),   -- enable in Ansible 2.12.
        # ('source', 'build', ['build']),   -- enable in Ansible 2.12.
        ('source', 'load', ['load_path']),
    ]

    def detect_build_cache_from(client):
        return client.module.params['build'] and client.module.params['build'].get('cache_from') is not None

    def detect_build_network(client):
        return client.module.params['build'] and client.module.params['build'].get('network') is not None

    def detect_build_target(client):
        return client.module.params['build'] and client.module.params['build'].get('target') is not None

    def detect_use_config_proxy(client):
        return client.module.params['build'] and client.module.params['build'].get('use_config_proxy') is not None

    def detect_etc_hosts(client):
        return client.module.params['build'] and bool(client.module.params['build'].get('etc_hosts'))

    option_minimal_versions = dict()
    option_minimal_versions["build.cache_from"] = dict(docker_py_version='2.1.0', docker_api_version='1.25', detect_usage=detect_build_cache_from)
    option_minimal_versions["build.network"] = dict(docker_py_version='2.4.0', docker_api_version='1.25', detect_usage=detect_build_network)
    option_minimal_versions["build.target"] = dict(docker_py_version='2.4.0', detect_usage=detect_build_target)
    option_minimal_versions["build.use_config_proxy"] = dict(docker_py_version='3.7.0', detect_usage=detect_use_config_proxy)
    option_minimal_versions["build.etc_hosts"] = dict(docker_py_version='2.6.0', docker_api_version='1.27', detect_usage=detect_etc_hosts)

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        required_if=required_if,
        supports_check_mode=True,
        min_docker_version='1.8.0',
        min_docker_api_version='1.20',
        option_minimal_versions=option_minimal_versions,
    )

    if client.module.params['state'] == 'build':
        client.module.warn('The "build" state has been deprecated for a long time '
                           'and will be removed in Ansible 2.11. Please use '
                           '"present", which has the same meaning as "build".')
        client.module.params['state'] = 'present'
    if client.module.params['use_tls']:
        client.module.warn('The "use_tls" option has been deprecated for a long time '
                           'and will be removed in Ansible 2.11. Please use the'
                           '"tls" and "validate_certs" options instead.')

    if not is_valid_tag(client.module.params['tag'], allow_empty=True):
        client.fail('"{0}" is not a valid docker tag!'.format(client.module.params['tag']))

    build_options = dict(
        container_limits='container_limits',
        dockerfile='dockerfile',
        http_timeout='http_timeout',
        nocache='nocache',
        path='path',
        pull='pull',
        rm='rm',
        buildargs='args',
    )
    for option, build_option in build_options.items():
        default_value = None
        if option in ('rm', ):
            default_value = True
        elif option in ('nocache', ):
            default_value = False
        if client.module.params[option] != default_value:
            if client.module.params['build'] is None:
                client.module.params['build'] = dict()
            if client.module.params['build'].get(build_option, default_value) != default_value:
                client.fail('Cannot specify both %s and build.%s!' % (option, build_option))
            client.module.params['build'][build_option] = client.module.params[option]
            client.module.warn('Please specify build.%s instead of %s. The %s option '
                               'has been renamed and will be removed in Ansible 2.12.' % (build_option, option, option))
    if client.module.params['source'] == 'build':
        if (not client.module.params['build'] or not client.module.params['build'].get('path')):
            client.fail('If "source" is set to "build", the "build.path" option must be specified.')
        if client.module.params['build'].get('pull') is None:
            client.module.warn("The default for build.pull is currently 'yes', but will be changed to 'no' in Ansible 2.12. "
                               "Please set build.pull explicitly to the value you need.")
            client.module.params['build']['pull'] = True  # TODO: change to False in Ansible 2.12

    if client.module.params['state'] == 'present' and client.module.params['source'] is None:
        # Autodetection. To be removed in Ansible 2.12.
        if (client.module.params['build'] or dict()).get('path'):
            client.module.params['source'] = 'build'
        elif client.module.params['load_path']:
            client.module.params['source'] = 'load'
        else:
            client.module.params['source'] = 'pull'
        client.module.warn('The value of the "source" option was determined to be "%s". '
                           'Please set the "source" option explicitly. Autodetection will '
                           'be removed in Ansible 2.12.' % client.module.params['source'])

    if client.module.params['force']:
        client.module.params['force_source'] = True
        client.module.params['force_absent'] = True
        client.module.params['force_tag'] = True
        client.module.warn('The "force" option will be removed in Ansible 2.12. Please '
                           'use the "force_source", "force_absent" or "force_tag" option '
                           'instead, depending on what you want to force.')

    try:
        results = dict(
            changed=False,
            actions=[],
            image={}
        )

        ImageManager(client, results)
        client.module.exit_json(**results)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc())
    except RequestException as e:
        client.fail('An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'.format(e), exception=traceback.format_exc())
def main():
    argument_spec = dict(
        name=dict(type='str', required=True, aliases=['network_name']),
        connected=dict(type='list',
                       default=[],
                       elements='str',
                       aliases=['containers']),
        state=dict(type='str',
                   default='present',
                   choices=['present', 'absent']),
        driver=dict(type='str', default='bridge'),
        driver_options=dict(type='dict', default={}),
        force=dict(type='bool', default=False),
        appends=dict(type='bool', default=False, aliases=['incremental']),
        ipam_driver=dict(type='str'),
        ipam_driver_options=dict(type='dict'),
        ipam_options=dict(type='dict',
                          default={},
                          options=dict(
                              subnet=dict(type='str'),
                              iprange=dict(type='str'),
                              gateway=dict(type='str'),
                              aux_addresses=dict(type='dict'),
                          ),
                          removed_in_version='2.12'),
        ipam_config=dict(type='list',
                         elements='dict',
                         options=dict(
                             subnet=dict(type='str'),
                             iprange=dict(type='str'),
                             gateway=dict(type='str'),
                             aux_addresses=dict(type='dict'),
                         )),
        enable_ipv6=dict(type='bool'),
        internal=dict(type='bool'),
        labels=dict(type='dict', default={}),
        debug=dict(type='bool', default=False),
        scope=dict(type='str', choices=['local', 'global', 'swarm']),
        attachable=dict(type='bool'),
    )

    mutually_exclusive = [('ipam_config', 'ipam_options')]

    option_minimal_versions = dict(
        scope=dict(docker_py_version='2.6.0', docker_api_version='1.30'),
        attachable=dict(docker_py_version='2.0.0', docker_api_version='1.26'),
        labels=dict(docker_api_version='1.23'),
        ipam_driver_options=dict(docker_py_version='2.0.0'),
    )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        mutually_exclusive=mutually_exclusive,
        supports_check_mode=True,
        min_docker_version='1.10.0',
        min_docker_api_version='1.22',
        # "The docker server >= 1.10.0"
        option_minimal_versions=option_minimal_versions,
    )

    try:
        cm = DockerNetworkManager(client)
        client.module.exit_json(**cm.results)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e),
                    exception=traceback.format_exc())
    except RequestException as e:
        client.fail(
            'An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'
            .format(e),
            exception=traceback.format_exc())
def main():
    argument_spec = dict(
        containers=dict(type='bool', default=False),
        containers_filters=dict(type='dict'),
        images=dict(type='bool', default=False),
        images_filters=dict(type='dict'),
        networks=dict(type='bool', default=False),
        networks_filters=dict(type='dict'),
        volumes=dict(type='bool', default=False),
        volumes_filters=dict(type='dict'),
        builder_cache=dict(type='bool', default=False),
    )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        # supports_check_mode=True,
        min_docker_api_version='1.25',
        min_docker_version='2.1.0',
    )

    # Version checks
    cache_min_version = '3.3.0'
    if client.module.params[
            'builder_cache'] and client.docker_py_version < LooseVersion(
                cache_min_version):
        msg = "Error: Docker SDK for Python's version is %s. Minimum version required for builds option is %s. Use `pip install --upgrade docker` to upgrade."
        client.fail(msg % (docker_version, cache_min_version))

    try:
        result = dict()

        if client.module.params['containers']:
            filters = clean_dict_booleans_for_docker_api(
                client.module.params.get('containers_filters'))
            res = client.prune_containers(filters=filters)
            result['containers'] = res.get('ContainersDeleted') or []
            result['containers_space_reclaimed'] = res['SpaceReclaimed']

        if client.module.params['images']:
            filters = clean_dict_booleans_for_docker_api(
                client.module.params.get('images_filters'))
            res = client.prune_images(filters=filters)
            result['images'] = res.get('ImagesDeleted') or []
            result['images_space_reclaimed'] = res['SpaceReclaimed']

        if client.module.params['networks']:
            filters = clean_dict_booleans_for_docker_api(
                client.module.params.get('networks_filters'))
            res = client.prune_networks(filters=filters)
            result['networks'] = res.get('NetworksDeleted') or []

        if client.module.params['volumes']:
            filters = clean_dict_booleans_for_docker_api(
                client.module.params.get('volumes_filters'))
            res = client.prune_volumes(filters=filters)
            result['volumes'] = res.get('VolumesDeleted') or []
            result['volumes_space_reclaimed'] = res['SpaceReclaimed']

        if client.module.params['builder_cache']:
            res = client.prune_builds()
            result['builder_cache_space_reclaimed'] = res['SpaceReclaimed']

        client.module.exit_json(**result)
    except DockerException as e:
        client.fail('An unexpected docker error occurred: {0}'.format(e),
                    exception=traceback.format_exc())
    except RequestException as e:
        client.fail(
            'An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'
            .format(e),
            exception=traceback.format_exc())