Skip to content

Instantly share code, notes, and snippets.

@misTrasteos
Created April 27, 2022 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misTrasteos/e08690bc3321ed5bd3c18368e461db2e to your computer and use it in GitHub Desktop.
Save misTrasteos/e08690bc3321ed5bd3c18368e461db2e to your computer and use it in GitHub Desktop.
Ansible dynamic inventory add_host example
# ansible-playbook -e new_machine_name=new_machine playbook.yaml
---
- name: "Provision machine"
hosts: "localhost"
tasks:
- name: "Create machine ..."
docker_container:
name: "{{ new_machine_name }}"
hostname: "{{ new_machine_name }}"
command: ["sleep", "infinity"]
image: "python:3-slim"
register: "docker_output"
- name: "output"
debug:
msg: "{{ docker_output }}"
- name: "Add to inventory ..."
add_host:
name: "{{ new_machine_name }}"
ansible_host: "{{ new_machine_name }}"
ansible_connection: "docker"
- name: "Do some stuff in the new created machine"
hosts: "{{ new_machine_name }}"
tasks:
- name: "get hostname"
ansible.builtin.command: "hostname"
register: "hostname"
- name: "show hostname"
debug:
msg: "{{ hostname.stdout }}"
- name: "Clean everything"
hosts: "localhost"
tasks:
- name: "Stop container"
docker_container:
name: "{{ new_machine_name }}"
state: "stopped"
- name: "Remove container"
docker_container:
name: "{{ new_machine_name }}"
state: "absent"
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment