Passing variables to ansible roles

Tasdik Rahman picture Tasdik Rahman · Mar 19, 2017 · Viewed 83.2k times · Source

I have my directory structure as this

└── digitalocean
    ├── README.md
    ├── play.yml
    └── roles
        ├── bootstrap_server
        │   └── tasks
        │       └── main.yml
        ├── create_new_user
        │   └── tasks
        │       └── main.yml
        ├── update
        │   └── tasks
        │       └── main.yml
        └── vimserver
            ├── files
            │   └── vimrc_server
            └── tasks
                └── main.yml

When I am creating a user under the role create_new_user, I was hard coding the user name as

---
- name: Creating a user named username on the specified web server.
  user: 
    name: username
    state: present
    shell: /bin/bash
    groups: admin
    generate_ssh_key: yes
    ssh_key_bits: 2048
    ssh_key_file: .ssh/id_rsa

- name: Copy .ssh/id_rsa from host box to the remote box for user username
  become: true
  copy: 
    src: ~/.ssh/id_rsa.pub
    dest: /home/usernmame/.ssh/authorized_keys
    mode: 0600
    owner: username
    group: username

One way of solving this may be to create a var/main.yml and put the username there. But I wanted something through which I can specify the username at play.yml level. As I am also using the username in the role vimrcserver.

I am calling the roles using play.yml

---
- hosts: testdroplets
  roles:
    - update
    - bootstrap_server
    - create_new_user
    - vimserver

Would a template work here in this case? Couldn't find much from these SO questions

Answer

Tasdik Rahman picture Tasdik Rahman · Mar 19, 2017

I got it working by doing a

---
- hosts: testdroplets
  roles:
    - update
    - bootstrap_server
    - role: create_new_user
      username: username
    - role: vimserver
      username: username

on play.yml

Although would love to see a different approach then this

Docs: http://docs.ansible.com/ansible/playbooks_roles.html#roles

EDIT

I finally settled with a directory structure like

$ tree
.
├── README.md
├── ansible.cfg
├── play.yml
└── roles
    ├── bootstrap_server
    │   └── tasks
    │       └── main.yml
    ├── create_new_user
    │   ├── defaults
    │   │   └── main.yml
    │   └── tasks
    │       └── main.yml
    ├── update
    │   └── tasks
    │       └── main.yml
    └── vimserver
        ├── defaults
        │   └── main.yml
        ├── files
        │   └── vimrc_server
        └── tasks
            └── main.yml

Where I am creating a defaults/main.yml file inside the roles where I need the usage of {{username}}

If someone is interested in the code,