Skip to content

Instantly share code, notes, and snippets.

@jctanner
Last active December 2, 2018 18:37
Show Gist options
  • Save jctanner/7940393 to your computer and use it in GitHub Desktop.
Save jctanner/7940393 to your computer and use it in GitHub Desktop.
fakecloud
jtanner@u1304:~/ansible$ cat lib/ansible/runner/action_plugins/fakecloud.py
# action plugin
import re
import ansible.constants as C
from ansible import utils
from ansible import errors
from ansible.runner.return_data import ReturnData
from ansible.inventory.host import Host
from ansible.inventory.group import Group
class ActionModule(object):
### We need to be able to modify the inventory
BYPASS_HOST_LOOP = True
NEEDS_TMPPATH = False
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
options = {}
options.update(utils.parse_kv(module_args))
inventory_group = options.get("inventory_group") or "ec2_new"
if self.runner.noop_on_check(inject):
# in --check mode, always skip this module execution
return ReturnData(conn=conn, comm_ok=True, result=dict(skipped=True))
#result = self.runner._low_level_exec_command(conn, module_args, tmp, sudoable=True)
r = self.runner._execute_module(conn, tmp, 'fakecloud',
module_args, inject=inject)
if hasattr(r, 'result'):
# add the instances to inventory
for k in r.result['instances'].keys():
#import epdb; epdb.st()
self._add_host(k, inventory_group, r.result['instances'][k])
return r
def _add_host(self, name, groupname, facts):
#import epdb; epdb.st()
# redefine inventory and get group "all"
inventory = self.runner.inventory
allgroup = inventory.get_group('all')
# check if host in cache, add if not
if name in inventory._hosts_cache:
new_host = inventory._hosts_cache[name]
else:
new_host = Host(name)
# only groups can be added directly to inventory
inventory._hosts_cache[name] = new_host
allgroup.add_host(new_host)
# Add any variables to the new_host
for k in facts:
if not k in [ 'name', 'hostname', 'groupname', 'groups' ]:
new_host.set_variable(k, facts[k])
if not inventory.get_group(groupname):
new_group = Group(groupname)
inventory.add_group(new_group)
grp = inventory.get_group(groupname)
grp.add_host(new_host)
# add this host to the group cache
if inventory._groups_list is not None:
if group_name in inventory._groups_list:
if new_host.name not in inventory._groups_list[group_name]:
inventory._groups_list[group_name].append(new_host.name)
inventory.clear_pattern_cache()
jtanner@u1304:~/ansible$ cat library/cloud/fakecloud
#!/usr/bin/python
import sys
import time
def main():
module = AnsibleModule(
argument_spec = dict(
image = dict(),
count = dict(default='1'),
instance_tags = dict(type='dict'),
tags = dict(default='1'),
state = dict(default='present'),
inventory_group = dict(default='ec2_new')
)
)
#import epdb; epdb.st()
print "TEST"
count = int(module.params.get('count'))
tags = module.params.get('instance_tags')
instances = {}
instance_ids = range(0, count)
changed=True
for x in instance_ids:
thisid = "e" + str(x)
instances[thisid] = {}
instances[thisid]['public_ip'] = "127.0.0.1"
instances[thisid]['public_dns'] = thisid + ".lab.net"
instances[thisid]['instance_tags'] = tags
instances[thisid]['port'] = 22
instances[thisid]['ansible_ssh_host'] = '127.0.0.1'
if module.params.get('state') == 'absent':
pass
elif module.params.get('state') == 'present':
pass
module.exit_json(changed=changed, instance_ids=instance_ids, instances=instances)
# import module snippets
from ansible.module_utils.basic import *
main()
jtanner@u1304:~/issues/0000-auto-add-host$ cat site.yml
- hosts: localhost
connection: local
gather_facts: False
vars:
- tags:
foo: bar
baz: bang
tasks:
- debug: var=hostvars[inventory_hostname]
- fakecloud: image=1 count=2 state=present instance_tags="{{ tags }}"
register: result
#- debug: var=result
#- debug: var=hostvars
- hosts: ec2_new
gather_facts: False
tasks:
- debug: msg="{{ inventory_hostname }}"
- debug: var=hostvars[inventory_hostname]
- shell: uname -a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment