Ansible, how to add user to group only if user exists

I’m writing a playbook to setup development environment and build pipeline for a project. I would like to keep playbook decoupled from the actual infrastructure as much as possible, and just rely on groups, so I could setup the pipeline inside a local VM’s as well as on the bare hardware with the same command, just using different group limiter.

Now the problem is, with local Vagrant boxes I need to add user vagrant to docker group, where as with bare metal servers some arbitrary user. What is the best practice to handle these kind of variations in the playbook, keeping it as abstract as possible? Should I use behavioral parameters, host variables, group variables, conditionals or facts gathering for this kind of stuff?

  • log_driver param doesn't work on ansible 2.0
  • docker extra_host parameter expects a dictionary value for hostname, how can I use a variable?
  • How do I tag a local docker image with ansible docker_image module?
  • Unable to pull private image tag with docker and ansible
  • Ansible deploys Docker container to wrong Vagrant VM
  • problems using Ansible to run docker tasks on OS X
  • Is it even possible or reasonable to keep the playbook fully abstract, without any hardcoded values and adaptability to any environment?

  • Ansible - playbook dynamic verbosity
  • How to use wait_for in a two node cluster docker container deployment?
  • Ansible, running role multiple times with different parameter sets
  • How can i force remove a docker container using 'docker_container' module of Ansible?
  • Docker compose in production?
  • Is it desirable to use Ansible for creating a docker image
  • One Solution collect form web for “Ansible, how to add user to group only if user exists”

    To answer your specific question:

    Use a user variable that Vagrantfile overwrites.
    For example, it will be ubuntu if in aws or vagrant if you are in vagrant.

    A more theoretical answer:

    i had the same issue with vagrant builds and i decided to keep an ansible playbook somewhere so that all vagrant builds pick it up and execute it to setup the server.

    For example, the playbook looks like this:

     - hosts: all
         - name: remove apparmor
           apt: name=apparmor purge=true state=absent

    and then each of my vagrant repositories wget it and run it with

    box.vm.provision :ansible do |ansible|
        ansible.playbook = 'vagrant_extra.yml'
        ansible.sudo = true
        ansible.limit = 'all'

    The best solution i think would be to use packer to provision your own vagrant image that has all of those things pre-backed in there so that

    1. you dont need to waste time setting up the image yourself, and
    2. your boxes are the same as the “prod” boxes.
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.