当前位置: 首页>>代码示例>>Python>>正文


Python basic.AnsibleModule方法代码示例

本文整理汇总了Python中ansible.module_utils.basic.AnsibleModule方法的典型用法代码示例。如果您正苦于以下问题:Python basic.AnsibleModule方法的具体用法?Python basic.AnsibleModule怎么用?Python basic.AnsibleModule使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ansible.module_utils.basic的用法示例。


在下文中一共展示了basic.AnsibleModule方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    module = AnsibleModule(
        argument_spec={
            'jenkins_home': {'default': '/var/lib/jenkins'},
            'update_center_id': {'required': True},
            'update_center_url': {'required': True}
        }
    )
    update_ctr_config = os.path.join(module.params['jenkins_home'],
                                     'hudson.model.UpdateCenter.xml')
    tree = ET.parse(update_ctr_config)
    if module.params['update_center_id'] == 'default':
        changed = set_default(tree, module.params['update_center_url'])
    else:
        changed = append(tree,
                         module.params['update_center_id'],
                         module.params['update_center_url'])
    if changed:
        tree.write(update_ctr_config, encoding='UTF-8')
    module.exit_json(changed=changed) 
开发者ID:RedHatQE,项目名称:cinch,代码行数:22,代码来源:jenkins_update_center.py

示例2: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        name_prefix=dict(type='str'))
    )
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    name_prefix = module.params['name_prefix']

    try:
        groups = []
        for group in ram_connect(module).list_groups():
            if name_prefix and not group.name.startswith(name_prefix):
                continue
            groups.append(group.read())
        module.exit_json(changed=False, groups=groups)
    except Exception as e:
        module.fail_json(msg=str("Unable to list groups, error:{0}".format(e))) 
开发者ID:alibaba,项目名称:alibaba.alicloud,代码行数:23,代码来源:ali_ram_group_info.py

示例3: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        user_name=dict(type='str', aliases=['name'])
    ))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")
    try:
        access_key = []
        for access in ram_connect(module).list_access_keys(**module.params):
            access_key.append(access.read())
        module.exit_json(changed=False, access_keys=access_key)
    except Exception as e:
        module.fail_json(msg=str("Unable to list access_keys, error:{0}".format(e))) 
开发者ID:alibaba,项目名称:alibaba.alicloud,代码行数:18,代码来源:ali_ram_access_key_info.py

示例4: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        name_prefix=dict(type='str')),
        user_ids=dict(type='list', elements='str')
    )
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    name_prefix = module.params['name_prefix']
    user_ids = module.params['user_ids']
    try:
        users = []
        for user in ram_connect(module).list_users():
            if name_prefix and not user.name.startswith(name_prefix):
                continue
            if user_ids and user.user_id not in user_ids:
                continue
            users.append(user.read())
        module.exit_json(changed=False, users=users)
    except Exception as e:
        module.fail_json(msg=str("Unable to list users, error:{0}".format(e))) 
开发者ID:alibaba,项目名称:alibaba.alicloud,代码行数:26,代码来源:ali_ram_user_info.py

示例5: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        name_prefix=dict(type='str'))
    )
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    name_prefix = module.params['name_prefix']

    try:
        policies = []
        for policy in ram_connect(module).list_policies():
            if name_prefix and not policy.name.startswith(name_prefix):
                continue
            policies.append(policy.read())
        module.exit_json(changed=False, policies=policies)
    except Exception as e:
        module.fail_json(msg=str("Unable to list groups, error:{0}".format(e))) 
开发者ID:alibaba,项目名称:alibaba.alicloud,代码行数:23,代码来源:ali_ram_policy_info.py

示例6: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        db_instance_id=dict(type='str', aliases=['instance_id'], required=True),
        name_prefix=dict(type='str')
    ))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json("Package 'footmark' required for this module.")

    # Get values of variable
    db_instance_id = module.params['db_instance_id']
    name_prefix = module.params['name_prefix']
    result = []
    try:
        rds = rds_connect(module)
        for account in rds.describe_accounts(db_instance_id=db_instance_id):
            if name_prefix and not account.name.startswith(name_prefix):
                continue
            result.append(account.read())
        module.exit_json(changed=False, rds_accounts=result)
    except Exception as e:
        module.fail_json(msg="Unable to describe rds accounts, and got an error: {0}.".format(e)) 
开发者ID:alibaba,项目名称:alibaba.alicloud,代码行数:27,代码来源:ali_rds_account_info.py

示例7: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    module = AnsibleModule(
      argument_spec = dict(
        host = dict(required=True),
        username = dict(required=True),
        password = dict(required=True)
      )
    )
    
    device = module.params.get('host')
    username = module.params.get('username')
    password = module.params.get('password')

    url='http://' + host + '/ins'
    switchuser=username
    switchpassword=password

    myheaders={'content-type':'application/json-rpc'}
    
    payload=[
      {
        "jsonrpc": "2.0",
        "method": "cli",
        "params": {
          "cmd": "show version",
          "version": 1.2
        },
        "id": 1
      }
    ]
    response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()

    version = response['result']['body']['sys_ver_str']
    data = json.dumps({"version": version})
    module.exit_json(changed=False, msg=str(data)) 
开发者ID:PacktPublishing,项目名称:Mastering-Python-Networking-Second-Edition,代码行数:37,代码来源:custom_module_2.py

示例8: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    module = AnsibleModule(
        argument_spec=dict(
            instance_name=dict(type="str", required=True),
            instance_interfaces=dict(type="list", default=[]),
            instance_raw_config_args=dict(type="list", default=None),
            config_options=dict(type="dict", default={}),
            platform_box=dict(type="str", required=False),
            platform_box_version=dict(type="str"),
            platform_box_url=dict(type="str"),
            provider_name=dict(type="str", default="virtualbox"),
            provider_memory=dict(type="int", default=512),
            provider_cpus=dict(type="int", default=2),
            provider_options=dict(type="dict", default={}),
            provider_override_args=dict(type="list", default=None),
            provider_raw_config_args=dict(type="list", default=None),
            provision=dict(type="bool", default=False),
            force_stop=dict(type="bool", default=False),
            state=dict(type="str", default="up", choices=["up", "destroy", "halt"]),
        ),
        supports_check_mode=False,
    )

    v = VagrantClient(module)

    if module.params["state"] == "up":
        v.up()

    if module.params["state"] == "destroy":
        v.destroy()

    if module.params["state"] == "halt":
        v.halt()

    module.exit_json(**module.result) 
开发者ID:ansible-community,项目名称:molecule-vagrant,代码行数:37,代码来源:vagrant.py

示例9: run_package_operation

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def run_package_operation(conda, name, version, state, dry_run, command_runner, on_failure, on_success):
    """
    Runs Conda package operation.

    This method is intentionally decoupled from `AnsibleModule` to allow it to be easily tested in isolation.
    :param conda: location of the Conda executable
    :param name: name of the package of interest
    :param version: version of the package (`None` for latest)
    :param state: state the package should be in
    :param dry_run: will "pretend" to make changes only if `True`
    :param command_runner: method that executes a given Conda command (given as list of string arguments), which returns
    JSON and returns a tuple where the first argument is the outputted JSON and the second is anything written to stderr
    :param on_failure: method that takes any kwargs to be called on failure
    :param on_success: method that takes any kwargs to be called on success
    """
    correct_version_installed = check_package_installed(command_runner, conda, name, version)

    # TODO: State should be an "enum" (or whatever the Py2.7 equivalent is)
    if not correct_version_installed and state != 'absent':
        try:
            output, stderr = install_package(command_runner, conda, name, version, dry_run=dry_run)
            on_success(changed=True, output=output, stderr=stderr)
        except CondaPackageNotFoundError:
            on_failure(msg='Conda package "%s" not found' % (get_install_target(name, version, )))

    elif state == 'absent':
        try:
            output, stderr = uninstall_package(command_runner, conda, name, dry_run=dry_run)
            on_success(changed=True, output=output, stderr=stderr)
        except CondaPackageNotFoundError:
            on_success(changed=False)

    else:
        on_success(changed=False) 
开发者ID:UDST,项目名称:ansible-conda,代码行数:36,代码来源:conda.py

示例10: _main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def _main():
    """
    Entrypoint.
    """
    module = AnsibleModule(
        argument_spec={
            'name': {'required': True, 'type': 'str'},
            'version': {'default': None, 'required': False, 'type': 'str'},
            'state': {
                'default': 'present',
                'required': False,
                'choices': ['present', 'absent', 'latest']
            },
            'channels': {'default': None, 'required': False},
            'executable': {'default': None, 'required': False},
            'extra_args': {'default': None, 'required': False, 'type': 'str'}
        },
        supports_check_mode=True)

    conda = find_conda(module.params['executable'])
    name = module.params['name']
    state = module.params['state']
    version = module.params['version']

    if state == 'latest' and version is not None:
        module.fail_json(msg='`version` must not be set if `state == "latest"` (`latest` upgrades to newest version)')

    def command_runner(command):
        return _run_conda_command(module, command)

    run_package_operation(
        conda, name, version, state, module.check_mode, command_runner, module.fail_json, module.exit_json) 
开发者ID:UDST,项目名称:ansible-conda,代码行数:34,代码来源:conda.py

示例11: run_module

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def run_module():
    '''Run this module'''
    module_args = dict(
        oc_bin=dict(type='path', required=True),
        oc_conf=dict(type='path', required=True),
        oc_namespace=dict(type='str', required=True),
        cluster_name=dict(type='str', required=True),
        exclude_node=dict(type='str', required=True),
    )
    module = AnsibleModule(
        supports_check_mode=False,
        argument_spec=module_args
    )
    oc_bin = module.params['oc_bin']
    oc_conf = '--config={}'.format(module.params['oc_conf'])
    oc_namespace = '--namespace={}'.format(module.params['oc_namespace'])
    cluster_name = module.params['cluster_name']
    exclude_node = module.params['exclude_node']

    oc_exec = [oc_bin, oc_conf, oc_namespace]

    # create a nodes to find a pod on; We don't want to try to execute on a
    # pod running on a "NotReady" node or the inventory_hostname node because
    # the pods might not actually be alive.
    valid_nodes = get_valid_nodes(module, [oc_bin, oc_conf], exclude_node)

    # Need to find an alive pod to run gluster commands in.
    pod_name = select_pod(module, oc_exec, cluster_name, valid_nodes)

    check_volumes(module, oc_exec, pod_name)

    result = {'changed': False}
    module.exit_json(**result) 
开发者ID:RedHatOfficial,项目名称:ansible-redhat_openshift_utils,代码行数:35,代码来源:glusterfs_check_containerized.py

示例12: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    '''
    ansible oc module for services
    '''

    module = AnsibleModule(
        argument_spec=dict(
            kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
            state=dict(default='present', type='str',
                       choices=['present', 'absent', 'list']),
            debug=dict(default=False, type='bool'),
            namespace=dict(default='default', type='str'),
            all_namespaces=dict(defaul=False, type='bool'),
            name=dict(default=None, type='str'),
            files=dict(default=None, type='list'),
            kind=dict(required=True, type='str'),
            delete_after=dict(default=False, type='bool'),
            content=dict(default=None, type='dict'),
            force=dict(default=False, type='bool'),
            selector=dict(default=None, type='str'),
            field_selector=dict(default=None, type='str'),
        ),
        mutually_exclusive=[["content", "files"], ["selector", "name"], ["field_selector", "name"]],

        supports_check_mode=True,
    )
    rval = OCObject.run_ansible(module.params, module.check_mode)
    if 'failed' in rval:
        module.fail_json(**rval)

    module.exit_json(**rval) 
开发者ID:RedHatOfficial,项目名称:ansible-redhat_openshift_utils,代码行数:33,代码来源:oc_obj.py

示例13: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    argument_spec = dict(
        endpoint=dict(required=False, default=None),
        application_key=dict(required=False, default=None),
        application_secret=dict(required=False, default=None),
        consumer_key=dict(required=False, default=None),
        state=dict(default='present', choices=['present', 'absent']),
        name=dict(required=True),
        service=dict(choices=['boot', 'dns', 'vrack', 'reverse', 'monitoring',
                              'install', 'status', 'list', 'template',
                              'terminate', 'getmac'], required=True),
        domain=dict(required=False, default=None),
        ip=dict(required=False, default=None),
        vrack=dict(required=False, default=None),
        boot=dict(default='harddisk', choices=['harddisk', 'rescue']),
        force_reboot=dict(required=False, type='bool', default=False),
        template=dict(required=False, default=None),
        hostname=dict(required=False, default=None),
        max_retry=dict(required=False, default='10'),
        sleep=dict(required=False, default='10'),
        ssh_key_name=dict(required=False, default=None),
        use_distrib_kernel=dict(required=False, type='bool', default=False),
        link_type=dict(required=False, default='private',
                       choices=['public', 'private'])
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    om = OVHModule(module, module.check_mode, module.params)
    error, changed, result = om.run()
    if error is None:
        module.exit_json(changed=changed, **result)
    else:
        module.fail_json(msg=error, **result) 
开发者ID:synthesio,项目名称:infra-ovh-ansible-module,代码行数:39,代码来源:ovh.py

示例14: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    module = AnsibleModule(
        argument_spec={
            'file': {'required': True},
            'line': {'required': False},
            'method': {'choices': ['regex', 'simple'], 'default': 'simple'}
        }
    )
    # First sanity check that the file exists and is not a directory or such
    if not path.exists(module.params['file']) or \
       not path.isfile(module.params['file']):
        module.exit_json(changed=False, exists=False, present=False)
    # Create the method that will do the matching
    if module.params['method'] == 'regex':
        expression = re.compile(module.params['line'])

        def matcher(x):
            return expression.search(x) is not None
    else:
        def matcher(x):
            return x == module.params['line']
    # Read the file, line by line, and check for matches
    with open(module.params['file'], 'r') as reader:
        for line in reader.readlines():
            if matcher(line):
                module.exit_json(changed=False, exists=True, present=True)
    module.exit_json(changed=False, exists=True, present=False) 
开发者ID:RedHatQE,项目名称:cinch,代码行数:29,代码来源:line_match.py

示例15: main

# 需要导入模块: from ansible.module_utils import basic [as 别名]
# 或者: from ansible.module_utils.basic import AnsibleModule [as 别名]
def main():
    module = AnsibleModule(
        argument_spec=dict(
            key=dict(type='str', required=True),
            value=dict(type='str', required=True),
            etcd_client_port=dict(type='str', default="4001"),
        ),
    )

    key = module.params['key']
    value = module.params['value']
    endpoint = "http://127.0.0.1:%s" % module.params['etcd_client_port']

    def get_key(key):
        try:
            f = urlopen('%s/v2/keys%s' % (endpoint, key))
        except HTTPError as e:
            if e.code == 404:
                return None
            raise

        data = json.load(f)
        return data['node']['value']

    def set_key(key, value):
        with open(os.devnull, 'w') as fnull:
            check_call(['etcdctl', 'set', key, value], stdout=fnull)

    current_value = get_key(key)

    if current_value == value:
        module.exit_json(changed=False)

    set_key(key, value)

    module.exit_json(changed=True) 
开发者ID:laincloud,项目名称:lain,代码行数:38,代码来源:etcd_set_key.py


注:本文中的ansible.module_utils.basic.AnsibleModule方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。