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?

  • docker with ansible wait for database
  • Error while changing hostname inside docker container
  • Ansible Shell Cannot Pull Docker Image
  • Ansible roles task failing docker swarm node join
  • Ansible ignores remote_user switch
  • How to use the docker connection-plugin of ansible?
  • Is it even possible or reasonable to keep the playbook fully abstract, without any hardcoded values and adaptability to any environment?

  • Ansible-container setup errors
  • Ansible prompt_vars error: GetPassWarning: Cannot control echo on the terminal
  • How to pass securely SSH Keys to Docker Build?
  • Deploy Ansible project which include a docker-compose.yml
  • Plex using Ansible and Docker
  • How to do a health-check to Spring Boot app running inside Windows Docker Windows Container with Ansible?
  • 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.