Repository: ansible/ansible
Pull request: Support for pids_limit parameter in docker_container module
##### SUMMARY
This add pids_limit parameter support in docker_container module

Fixes #43337

##### ISSUE TYPE
- Feature Pull Request

##### COMPONENT NAME
docker_container

##### ADDITIONAL INFORMATION
Set pids limit as,

```paste below
- name: Run container with limiting pids
  docker_container:
     name: example
     image: nginx:latest
     state: started
     pids_limit: 100
```


Problem statement:
support for pids_limit parameter in docker_container module
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### SUMMARY
<!--- Explain the problem briefly -->

It appears ansible's docker_container module does not support the --pids-limit parameter.
Without pids-limit there does not appear to be a way to configure the limit of concurrent pids for a running container (example use-case: this is a requirement for the CIS docker benchmark for security hardening)
"pid_mode" does not appear to provide this functionality (if it, in fact does, it seems to be poorly documented, and quite limited).

##### ISSUE TYPE
<!--- Pick one below and delete the rest -->
 - Feature Idea
 
##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
docker_container
##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.4.0
```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->
DEFAULT_HOST_LIST(/Users/moi/.ansible.cfg) = [u'/Users/moi/hosts']
DEFAULT_REMOTE_USER(/Users/moi/.ansible.cfg) = twelcome 
DEFAULT_VAULT_PASSWORD_FILE(/Users/moi/.ansible.cfg) = /Users/moi/passwords
HOST_KEY_CHECKING(/Users/moi/.ansible.cfg) = False
##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->
N/A
##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->

<!--- Paste example playbooks or commands between quotes below -->
```yaml

```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
```

```

Hints from issue discussion:
Files identified in the description:
* [lib/ansible/modules/cloud/docker/docker_container.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/docker/docker_container.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @chouseknecht @cove @dusdanig @joshuaconner @kassiansun @softzilla @zfil
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->
cc @felixfontein
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->
cc @akshay196 @danihodovic @dariko @jwitko @tbouvet
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->
I would like to work on this issue. I will submit PR when I am done.
resolved_by_pr #49319

Commit message: Add changelog for pids_limit parameter

Signed-off-by: Akshay Gaikwad <akgaikwad001@gmail.com>

Patch to review:
diff --git a/changelogs/fragments/49319-docker_container-pids_limit.yaml b/changelogs/fragments/49319-docker_container-pids_limit.yaml
new file mode 100644
index 00000000000000..545dac12e4c3f1
--- /dev/null
+++ b/changelogs/fragments/49319-docker_container-pids_limit.yaml
@@ -0,0 +1,2 @@
+minor_changes:
+- "docker_container - Added support for ``pids_limit`` parameter in docker_container."
diff --git a/lib/ansible/modules/cloud/docker/docker_container.py b/lib/ansible/modules/cloud/docker/docker_container.py
index 4254b16a4415d6..fe879f61b402b7 100644
--- a/lib/ansible/modules/cloud/docker/docker_container.py
+++ b/lib/ansible/modules/cloud/docker/docker_container.py
@@ -408,6 +408,12 @@
     description:
       - Set the PID namespace mode for the container.
       - Note that docker-py < 2.0 only supports 'host'. Newer versions allow all values supported by the docker daemon.
+  pids_limit:
+    description:
+      - Set PID limit for the container. It accepts an integer value.
+      - Set -1 for unlimited PID.
+    type: int
+    version_added: "2.8"
   privileged:
     description:
       - Give extended privileges to the container.
@@ -1012,6 +1018,7 @@ def __init__(self, client):
         self.oom_score_adj = None
         self.paused = None
         self.pid_mode = None
+        self.pids_limit = None
         self.privileged = None
         self.purge_networks = None
         self.pull = None
@@ -1276,6 +1283,7 @@ def _host_config(self):
             device_write_bps='device_write_bps',
             device_read_iops='device_read_iops',
             device_write_iops='device_write_iops',
+            pids_limit='pids_limit',
         )
 
         if self.client.docker_py_version >= LooseVersion('1.9') and self.client.docker_api_version >= LooseVersion('1.22'):
@@ -1690,6 +1698,7 @@ def __init__(self, container, parameters):
         self.parameters_map['device_write_bps'] = 'device_write_bps'
         self.parameters_map['device_read_iops'] = 'device_read_iops'
         self.parameters_map['device_write_iops'] = 'device_write_iops'
+        self.parameters_map['pids_limit'] = 'pids_limit'
 
     def fail(self, msg):
         self.parameters.client.module.fail_json(msg=msg)
@@ -1814,6 +1823,7 @@ def has_different_configuration(self, image):
             device_write_bps=host_config.get('BlkioDeviceWriteBps'),
             device_read_iops=host_config.get('BlkioDeviceReadIOps'),
             device_write_iops=host_config.get('BlkioDeviceWriteIOps'),
+            pids_limit=host_config.get('PidsLimit'),
         )
         # Options which don't make sense without their accompanying option
         if self.parameters.restart_policy:
@@ -2782,6 +2792,7 @@ def detect_ipvX_address_usage():
             sysctls=dict(docker_py_version='1.10.0', docker_api_version='1.24'),
             userns_mode=dict(docker_py_version='1.10.0', docker_api_version='1.23'),
             uts=dict(docker_py_version='3.5.0', docker_api_version='1.25'),
+            pids_limit=dict(docker_py_version='1.10.0', docker_api_version='1.23'),
             # specials
             ipvX_address_supported=dict(docker_py_version='1.9.0', detect_usage=detect_ipvX_address_usage,
                                         usage_msg='ipv4_address or ipv6_address in networks'),
@@ -2937,6 +2948,7 @@ def main():
         output_logs=dict(type='bool', default=False),
         paused=dict(type='bool', default=False),
         pid_mode=dict(type='str'),
+        pids_limit=dict(type='int'),
         privileged=dict(type='bool', default=False),
         published_ports=dict(type='list', aliases=['ports'], elements='str'),
         pull=dict(type='bool', default=False),
diff --git a/test/integration/targets/docker_container/tasks/tests/options.yml b/test/integration/targets/docker_container/tasks/tests/options.yml
index 63013ad442a226..44e3d0a664b0db 100644
--- a/test/integration/targets/docker_container/tasks/tests/options.yml
+++ b/test/integration/targets/docker_container/tasks/tests/options.yml
@@ -2773,6 +2773,53 @@
     - pid_mode_3 is changed
   when: docker_py_version is version('2.0.0', '<')
 
+####################################################################
+## pids_limit ######################################################
+####################################################################
+
+- name: pids_limit
+  docker_container:
+    image: alpine:3.8
+    command: '/bin/sh -c "sleep 10m"'
+    name: "{{ cname }}"
+    state: started
+    pids_limit: 10
+    force_kill: yes
+  register: pids_limit_1
+
+- name: pids_limit (idempotency)
+  docker_container:
+    image: alpine:3.8
+    command: '/bin/sh -c "sleep 10m"'
+    name: "{{ cname }}"
+    state: started
+    pids_limit: 10
+    force_kill: yes
+  register: pids_limit_2
+
+- name: pids_limit (changed)
+  docker_container:
+    image: alpine:3.8
+    command: '/bin/sh -c "sleep 10m"'
+    name: "{{ cname }}"
+    state: started
+    pids_limit: 20
+    force_kill: yes
+  register: pids_limit_3
+
+- name: cleanup
+  docker_container:
+    name: "{{ cname }}"
+    state: absent
+    force_kill: yes
+  diff: no
+
+- assert:
+    that:
+    - pids_limit_1 is changed
+    - pids_limit_2 is not changed
+    - pids_limit_3 is changed
+
 ####################################################################
 ## privileged ######################################################
 ####################################################################


Code review comments:
diff_hunk: @@ -1690,6 +1698,7 @@ def __init__(self, container, parameters):
         self.parameters_map['device_write_bps'] = 'device_write_bps'
         self.parameters_map['device_read_iops'] = 'device_read_iops'
         self.parameters_map['device_write_iops'] = 'device_write_iops'
+        self.parameters_map['pids_limit'] = 'pids_limit'
path: lib/ansible/modules/cloud/docker/docker_container.py
text: @user1:
Sorry for not noticing this earlier, but this isn't necessary (and the four lines above aren't, either). The map is needed if the names are different (`expected_*` vs. `*`), and is not defined for most options. Can you remove this (and the four lines above)?

@author:
Make sense. Thank you for letting me know. I have made the changes.

@user1:
Thanks!