I want to have build some minimal example for ansible playbook, thus I do not want to have multiple files and dirs for each playbook.
I would like to make the single file contain everything.
I knew I can use localhost like following, then I can just run the playbook without inventory.
- name: Example playbook
hosts: localhost
connections: local
tasks:
- ansible.builtin.debug: "hello!"
I wonder how can I do similar thing but also define a simple inventory inside the playbook:
all:
hosts:
localhost:
ansible_connection: local
host1:
http_port: 80
maxRequestsPerChild: 808
ansible_host: 127.0.0.2
the hosts keyword in the playbook seems only accept list of strings
You cannot "embed" an inventory in the playbook, but you could dynamically build an inventory using the add_host
module.
E.g:
- hosts: localhost
gather_facts: false
tasks:
- add_host:
name: newhost1
groups:
- webservers
http_port: 80
maxRequestsPerChild: 808
ansible_host: 127.0.0.2
- hosts: webservers
gather_facts: false
tasks:
- ping:
Running this produces:
PLAY [localhost] ***************************************************************
TASK [add_host] ****************************************************************
changed: [localhost]
PLAY [webservers] **************************************************************
TASK [ping] ********************************************************************
ok: [newhost1]
PLAY RECAP *********************************************************************
localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
newhost1 : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0