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?

  • Ansible, running role multiple times with different parameter sets
  • Run Command Inside of Docker Container Using Ansible
  • Conductor container can't be found. Run `ansible-container build` first
  • Ansible - playbook dynamic verbosity
  • Ansible docker_container etc_hosts with variable key
  • Pass parameter (like -Des.node.name=“TestNode”) in docker run from Ansible or Fig
  • Is it even possible or reasonable to keep the playbook fully abstract, without any hardcoded values and adaptability to any environment?

  • why ansible always replaces double quotes with single quotes in templates?
  • Issues in ansible while working with docker
  • Creating docker swarm using ansible
  • Dockerized PostgreSQL: psql: FATAL: the database system is starting up
  • Install Gitlab with disabled sign up
  • Run 'docker volume create' 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
       tasks:
         - 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'
    end
    

    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.