Search code examples
roleansible

ansible: roles structure and variables


I use ansible for a while with standalone playbooks and now would like to configure role structure at my environment. This is folder structure(example, summarised)

├── hosts
├── playbooks
│   ├── project1-staging.yml
│   └── project1-production.yml
├── roles
│   └── project1-compile
│       ├── files
│       │   └── project1.conf
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml
│       ├── templates
│       └── vars
│           └── main.yml
│   └── ec2-create
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml
│       ├── templates
│       └── vars
│           └── main.yml
│   └── project1-deploy
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml
│       ├── templates
│       └── vars
│           └── main.yml
├── vars.yml

It looks straightforward. I would like to execute project1-staging.yml playbook to create a new staging environment for specific version, like that; ansible-playbook project1-staging.yml -e 'version=1'

and playbook below;

---
- name: deploy project1 (staging) {{ version }}
  hosts: local
  connection: local
  roles:
  #- project1-compile version={{ version }}
  - { role: ec2-create, project: project1,  count:1 }
  - { role: project1-compile, version: {{ version }}  }
  - { role: project1-deploy, version: {{ version }}, target: {{last_ec2}}  }

There are some problem at this structure and also i don't like it. - Is that proper way? - how can i use result of ec2-create role, i would like to deploy codes to server which is just created and i don't know id. - are there another method to pass parameters to roles?


Solution

  • Take a look at Inventory Modules. More specifically add_host module.


    Synopsis

    Use variables to create new hosts and groups in inventory for use in later plays of the same playbook. Takes variables so you can define the new hosts more fully.

    Examples

    # add host to group 'just_created' with variable foo=42
    - add_host: name={{ ip_from_ec2 }} groups=just_created foo=42
    
    # add a host with a non-standard port local to your machines
    - add_host: name={{ new_ip }}:{{ new_port }}
    
    # add a host alias that we reach through a tunnel
    - add_host: hostname={{ new_ip }}
                ansible_ssh_host={{ inventory_hostname }}
                ansible_ssh_port={{ new_port }}