Repository: ansible/ansible-modules-core

Issue:
docker_container removes published ports when used for restart
<!--- Verify first that your issue/request is not already reported in GitHub -->
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME

<!--- Name of the plugin/module/task -->

docker_container
##### ANSIBLE VERSION

<!--- Paste verbatim output from “ansible --version” between quotes below -->

```
ansible 2.1.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```
##### CONFIGURATION

<!---
Mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).
-->
##### OS / ENVIRONMENT

<!---
Mention the OS you are running Ansible from, and the OS you are
managing, or say “N/A” for anything that is not platform-specific.
-->

Ubuntu Trusty on EC2
##### SUMMARY

<!--- Explain the problem briefly -->

docker_container alters the ports when used to restart a docker contaienr
##### STEPS TO REPRODUCE

<!---
For bugs, show exactly how to reproduce the problem.
For new features, show how the feature would be used.
-->

<!--- Paste example playbooks or commands between quotes below -->

```
I wanted the equivalent of the below using docker_container
- name: restart containers
   shell: "docker stop {{ item }}; docker start {{ item }}"
   with_items: "{{ docker_names.stdout_lines }} "

this is my docker_container create task
- name: install lucee5 docker instance 1
docker_container:
docker_api_version: "{{ dockerapi_version }}"
etc_hosts: "{{ docker_extra_hosts }}"
name: "{{ site_prefix }}{{ docker_port }}"
image: "{{ site_docker_image }}"
state: started
restart_policy: on-failure
restart_retries: 5
pull: yes
published_ports:
- "{{ docker_port }}:8888"

this is my restart that fails
- name: restart container
docker_container:
api_version: "{{ dockerapi_version }}"
pull: no
name: "{{ item }}"
image: "{{ site_docker_image }}"
state: started
restart: yes
with_items: "{{ docker_names.stdout_lines }} "
```

<!--- You can also paste gist.github.com links for larger files -->
##### EXPECTED RESULTS

The restarted container should of had the same published port i.e.
0.0.0.0:8815->8888/tcp

<!--- What did you expect to happen when running the steps above? -->

the problem is 
after the creation of the container it has port of
0.0.0.0:8815->8888/tcp

but after the restart this is removed and hence 8815 on host is no longer mapped to 8888 on container
(ports output is now 8009/tcp, 8080/tcp, 8888/tcp  and it should be 8009/tcp, 8080/tcp, 0.0.0.0:8815->8888/tcp)

using the shell variant it works as expected.
##### ACTUAL RESULTS

<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

It all works

<!--- Paste verbatim command output between quotes below -->

```
TASK [restart containers] ****************************************************** task path: /var/lib/awx/projects/_5__idg_bitbucket_ansible/aws-update-site-code.yml:22 <172.31.38.101> ESTABLISH SSH CONNECTION FOR USER: ubuntu <172.31.38.101> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ubuntu -o ConnectTimeout=10 -o ControlPath=/tmp/ansible_tower_11VzYn/cp/ansible-ssh-%h-%p-%r 172.31.38.101 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo $HOME/.ansible/tmp/ansible-tmp-1472130784.34-220794800462734 `" && echo ansible-tmp-1472130784.34-220794800462734="` echo $HOME/.ansible/tmp/ansible-tmp-1472130784.34-220794800462734 `" ) && sleep 0'"'"'' <172.31.38.101> PUT /tmp/tmptHnFY8 TO /home/ubuntu/.ansible/tmp/ansible-tmp-1472130784.34-220794800462734/docker_container <172.31.38.101> SSH: EXEC sftp -b - -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ubuntu -o ConnectTimeout=10 -o ControlPath=/tmp/ansible_tower_11VzYn/cp/ansible-ssh-%h-%p-%r '[172.31.38.101]' <172.31.38.101> ESTABLISH SSH CONNECTION FOR USER: ubuntu <172.31.38.101> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ubuntu -o ConnectTimeout=10 -o ControlPath=/tmp/ansible_tower_11VzYn/cp/ansible-ssh-%h-%p-%r -tt 172.31.38.101 '/bin/sh -c '"'"'sudo -H -S -n -u root /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-vbxgltaucyynhgzltqurmkpjrmohhgwe; LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 /usr/bin/python /home/ubuntu/.ansible/tmp/ansible-tmp-1472130784.34-220794800462734/docker_container; rm -rf "/home/ubuntu/.ansible/tmp/ansible-tmp-1472130784.34-220794800462734/" > /dev/null 2>&1'"'"'"'"'"'"'"'"' && sleep 0'"'"'' changed: [172.31.38.101] => (item=pca8815) => {"ansible_facts": {"ansible_docker_container": {"AppArmorProfile": "", "Args": ["run"], "Config": {"AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": ["catalina.sh", "run"], "Domainname": "", "Entrypoint": null, "Env": ["PATH=/usr/local/tomcat/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C.UTF-8", "JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre", "JAVA_VERSION=8u72", "JAVA_DEBIAN_VERSION=8u72-b15-1~bpo8+1", "CA_CERTIFICATES_JAVA_VERSION=20140324", "CATALINA_HOME=/usr/local/tomcat", "TOMCAT_MAJOR=8", "TOMCAT_VERSION=8.0.32", "TOMCAT_TGZ_URL=https://www.apache.org/dist/tomcat/tomcat-8/v8.0.32/bin/apache-tomcat-8.0.32.tar.gz", "LUCEE_JARS_URL=http://snapshot.lucee.org/rest/update/provider/loader/5.0.0.228-SNAPSHOT", "LUCEE_JAVA_OPTS=-Xms256m -Xmx512m", "TERM=xterm"], "ExposedPorts": {"8009/tcp": {}, "8080/tcp": {}, "8888/tcp": {}}, "Hostname": "bf0ab3a35447", "Image": "idguk/lucee5:0.3", "Labels": {}, "OnBuild": null, "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": null, "WorkingDir": "/opt"}, "Created": "2016-08-25T13:13:01.27748365Z", "Driver": "devicemapper", "ExecIDs": null, "GraphDriver": {"Data": {"DeviceId": "44", "DeviceName": "docker-202:1-271495-f641f21a4059babc8e8f2461e3aee8f762836486114f375e34ebe5d7b856add9", "DeviceSize": "10737418240"}, "Name": "devicemapper"}, "HostConfig": {"AutoRemove": false, "Binds": [], "BlkioDeviceReadBps": null, "BlkioDeviceReadIOps": null, "BlkioDeviceWriteBps": null, "BlkioDeviceWriteIOps": null, "BlkioWeight": 0, "BlkioWeightDevice": null, "CapAdd": null, "CapDrop": null, "Cgroup": "", "CgroupParent": "", "ConsoleSize": [0, 0], "ContainerIDFile": "", "CpuCount": 0, "CpuPercent": 0, "CpuPeriod": 0, "CpuQuota": 0, "CpuShares": 0, "CpusetCpus": "", "CpusetMems": "", "Devices": null, "DiskQuota": 0, "Dns": null, "DnsOptions": null, "DnsSearch": null, "ExtraHosts": null, "GroupAdd": null, "IOMaximumBandwidth": 0, "IOMaximumIOps": 0, "IpcMode": "", "Isolation": "", "KernelMemory": 0, "Links": null, "LogConfig": {"Config": {}, "Type": "json-file"}, "Memory": 0, "MemoryReservation": 0, "MemorySwap": 0, "MemorySwappiness": -1, "NetworkMode": "default", "OomKillDisable": false, "OomScoreAdj": 0, "PidMode": "", "PidsLimit": 0, "PortBindings": null, "Privileged": false, "PublishAllPorts": false, "ReadonlyRootfs": false, "RestartPolicy": {"MaximumRetryCount": 0, "Name": ""}, "Runtime": "runc", "SecurityOpt": null, "ShmSize": 67108864, "UTSMode": "", "Ulimits": null, "UsernsMode": "", "VolumeDriver": "", "VolumesFrom": null}, "HostnamePath": "/var/lib/docker/containers/bf0ab3a354470979677e4b0cb4513372cc7f4351e5232a47d1d6c6f19f8bd479/hostname", "HostsPath": "/var/lib/docker/containers/bf0ab3a354470979677e4b0cb4513372cc7f4351e5232a47d1d6c6f19f8bd479/hosts", "Id": "bf0ab3a354470979677e4b0cb4513372cc7f4351e5232a47d1d6c6f19f8bd479", "Image": "sha256:c7a9c7f14b1ad1ca1a5036b21ed99418e4a9bcd2c35e83f61fbd58f664486d50", "LogPath": "/var/lib/docker/containers/bf0ab3a354470979677e4b0cb4513372cc7f4351e5232a47d1d6c6f19f8bd479/bf0ab3a354470979677e4b0cb4513372cc7f4351e5232a47d1d6c6f19f8bd479-json.log", "MountLabel": "", "Mounts": [], "Name": "/pca8815", "NetworkSettings": {"Bridge": "", "EndpointID": "e4fcd43fc87ab7378f73a6ee973aefe0c8b16327dde75e30653a6b8a9668dd42", "Gateway": "172.17.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "HairpinMode": false, "IPAddress": "172.17.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:02", "Networks": {"bridge": {"Aliases": null, "EndpointID": "e4fcd43fc87ab7378f73a6ee973aefe0c8b16327dde75e30653a6b8a9668dd42", "Gateway": "172.17.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAMConfig": null, "IPAddress": "172.17.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "Links": null, "MacAddress": "02:42:ac:11:00:02", "NetworkID": "e23b204c3ead343cd4b5dbf1c9bd8963b0d5765515122e5078b84064010e0ec4"}}, "Ports": {"8009/tcp": null, "8080/tcp": null, "8888/tcp": null}, "SandboxID": "37ce504c47cc80c70c4d9bda33667c371f2fd8898c0f4d60b3d2d0a0e7eea634", "SandboxKey": "/var/run/docker/netns/37ce504c47cc", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null}, "Path": "catalina.sh", "ProcessLabel": "", "ResolvConfPath": "/var/lib/docker/containers/bf0ab3a354470979677e4b0cb4513372cc7f4351e5232a47d1d6c6f19f8bd479/resolv.conf", "RestartCount": 0, "State": {"Dead": false, "Error": "", "ExitCode": 0, "FinishedAt": "0001-01-01T00:00:00Z", "OOMKilled": false, "Paused": false, "Pid": 7181, "Restarting": false, "Running": true, "StartedAt": "2016-08-25T13:13:01.565460684Z", "Status": "running"}}}, "changed": true, "invocation": {"module_args": {"api_version": "1.21", "blkio_weight": null, "cacert_path": null, "capabilities": null, "cert_path": null, "command": null, "cpu_period": null, "cpu_quota": null, "cpu_shares": null, "cpuset_cpus": null, "cpuset_mems": null, "debug": false, "detach": true, "devices": null, "dns_opts": null, "dns_search_domains": null, "dns_servers": null, "docker_host": null, "entrypoint": null, "env": null, "env_file": null, "etc_hosts": null, "exposed_ports": null, "filter_logger": false, "force_kill": false, "groups": null, "hostname": null, "image": "idguk/lucee5:0.3", "interactive": false, "ipc_mode": null, "keep_volumes": true, "kernel_memory": null, "key_path": null, "kill_signal": null, "labels": null, "links": null, "log_driver": "json-file", "log_options": null, "mac_address": null, "memory": "0", "memory_reservation": null, "memory_swap": null, "memory_swappiness": null, "name": "pca8815", "network_mode": null, "networks": null, "oom_killer": null, "paused": false, "pid_mode": null, "privileged": false, "published_ports": null, "pull": false, "purge_networks": null, "read_only": false, "recreate": false, "restart": true, "restart_policy": null, "restart_retries": 0, "security_opts": null, "shm_size": null, "ssl_version": null, "state": "started", "stop_signal": null, "stop_timeout": null, "timeout": null, "tls": null, "tls_hostname": null, "tls_verify": null, "trust_image_content": false, "tty": false, "ulimits": null, "user": null, "uts": null, "volume_driver": null, "volumes": null, "volumes_from": null}, "module_name": "docker_container"}, "item": "pca8815"}
```



Discussion:
<!-- @ablack-idguk: Thanks for filing this bug report! -->

@ansible ping, this issue is waiting for your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_bug_new --->

@ansible, ping. This issue is still waiting on your response.
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)

<!--- boilerplate: issue_renotify_maintainer --->


Resolving patch:
diff --git a/cloud/docker/docker_container.py b/cloud/docker/docker_container.py
--- a/cloud/docker/docker_container.py
+++ b/cloud/docker/docker_container.py
@@ -1927,7 +1927,7 @@ def main():
         recreate=dict(type='bool', default=False),
         restart=dict(type='bool', default=False),
         restart_policy=dict(type='str', choices=['no', 'on-failure', 'always', 'unless-stopped']),
-        restart_retries=dict(type='int', default=0),
+        restart_retries=dict(type='int', default=None),
         shm_size=dict(type='str'),
         security_opts=dict(type='list'),
         state=dict(type='str', choices=['absent', 'present', 'started', 'stopped'], default='started'),


Test patch: