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?

  • Why ansible keeps recreating docker containers with state “started”
  • Ansible - playbook dynamic verbosity
  • Docker build not using cache when running through ansible
  • Error trying to install Ansible in Jenkins image
  • Ansible - using register with a loop
  • Udeploy not projecting the data
  • Is it even possible or reasonable to keep the playbook fully abstract, without any hardcoded values and adaptability to any environment?

  • How can i force remove a docker container using 'docker_container' module of Ansible?
  • One or more undefined variables: 'dict object' has no attribute 'SSH_AUTH_SOCK'
  • Launch Docker Container using ansible-playbook from a locally available docker image
  • Add/edit files inside a docker container using a remotely?
  • Alternating provisioning with Vagrant
  • How Docker and Ansible fit together to implement Continuos Delivery/Continuous Deployment
  • 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.