コード例 #1
0
def gather_vcsa_facts(module, vcsa_url, vcsa_username, vcsa_password,
                      validate_certs):
    """Gather server facts"""

    facts = {}

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        (rc, session_id) = request(url=vcsa_url + "/com/vmware/cis/session",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers,
                                   method='POST')
    except:
        err = get_exception()
        module.fail_json(
            msg="Failed to establish a session and authenticate. Error [%s]." %
            str(err))

    headers.update({'vmware-api-session-id': session_id['value']})

    try:
        (rc,
         system_version) = request(url=vcsa_url + "/appliance/system/version",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get appliance version. Error [%s]." %
                         str(err))

    facts['vcsa_product'] = system_version['value']['product'].strip()
    facts['vcsa_type'] = system_version['value']['type'].strip()
    facts['vcsa_build'] = system_version['value']['build'].strip()
    facts['vcsa_releasedate'] = system_version['value']['releasedate'].strip()
    facts['vcsa_version'] = system_version['value']['version'].strip()
    facts['vcsa_version_number'] = int(
        system_version['value']['version'].strip().split(".")[0] +
        system_version['value']['version'].strip().split(".")[1] +
        system_version['value']['version'].strip().split(".")[2])
    facts['vcsa_install_time'] = system_version['value']['install_time'].strip(
    )

    module.exit_json(ansible_facts=facts)
コード例 #2
0
def check_vcsa_accounts(module, vcsa_url, vcsa_username, vcsa_password,
                        account, enabled, full_name, password_expires,
                        valid_days, email, validate_certs):
    """Inform the user what would change if the module were run"""

    would_be_changed = []
    changed_status = False

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        (rc, session_id) = request(url=vcsa_url + "/com/vmware/cis/session",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers,
                                   method='POST')
    except:
        err = get_exception()
        module.fail_json(
            msg="Failed to establish a session and authenticate. Error [%s]." %
            str(err))

    headers.update({'vmware-api-session-id': session_id['value']})

    try:
        (rc,
         system_version) = request(url=vcsa_url + "/appliance/system/version",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get appliance version. Error [%s]." %
                         str(err))

    appliance_version = system_version['value']['version']
    if appliance_version.startswith('6.7'):
        try:
            (rc, local_account) = request(
                url=vcsa_url + "/appliance/local-accounts/%s" % account,
                url_username=vcsa_username,
                url_password=vcsa_password,
                validate_certs=validate_certs,
                headers=headers)
        except:
            err = get_exception()
            module.fail_json(
                msg="Failed to get local account %s. Error [%s]." %
                (account, str(err)))

        # check if account is enabled
        if local_account['value']['enabled'] is not enabled:
            would_be_changed.append('enabled')
            changed_status = True

        # check full name
        if full_name:
            if local_account['value']['fullname'] != full_name:
                would_be_changed.append('full_name')
                changed_status = True
        else:
            if local_account['value']['fullname'] != account:
                would_be_changed.append('full_name')
                changed_status = True

        # check password expiration
        if password_expires:
            # password expiration is disabled
            if local_account['value']['max_days_between_password_change'] in (
                    99999, -1):
                would_be_changed.append('password_expires')
                changed_status = True
            else:
                if local_account['value'][
                        'max_days_between_password_change'] is not valid_days:
                    would_be_changed.append('valid_days')
                    changed_status = True
                if local_account['value']['email'] != email:
                    would_be_changed.append('email')
                    changed_status = True
        else:
            # password expiration is not disabled
            if local_account['value'][
                    'max_days_between_password_change'] not in (99999, -1):
                would_be_changed.append('password_expires')
                changed_status = True

        if changed_status:
            if len(would_be_changed) > 2:
                message = ', '.join(would_be_changed[:-1]) + ', and ' + str(
                    would_be_changed[-1]) + ' would be changed.'
            elif len(would_be_changed) == 2:
                message = ' and '.join(would_be_changed) + ' would be changed.'
            elif len(would_be_changed) == 1:
                message = would_be_changed[0] + ' would be changed.'
        else:
            message = 'all settings are already configured.'

        module.exit_json(changed=changed_status, msg=message)
    else:
        module.fail_json(msg="Appliance version %s not supported!" %
                         appliance_version)
コード例 #3
0
def configure_vcsa_accounts(module, vcsa_url, vcsa_username, vcsa_password,
                            account, enabled, full_name, password_expires,
                            valid_days, email, validate_certs):
    """Configure vCSA accounts"""

    changed = []
    changed_status = False

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        (rc, session_id) = request(url=vcsa_url + "/com/vmware/cis/session",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers,
                                   method='POST')
    except:
        err = get_exception()
        module.fail_json(
            msg="Failed to establish a session and authenticate. Error [%s]." %
            str(err))

    headers.update({'vmware-api-session-id': session_id['value']})

    try:
        (rc, local_account) = request(url=vcsa_url +
                                      "/appliance/local-accounts/%s" % account,
                                      url_username=vcsa_username,
                                      url_password=vcsa_password,
                                      validate_certs=validate_certs,
                                      headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get local account %s. Error [%s]." %
                         (account, str(err)))

    # check if account is enabled
    if local_account['value']['enabled'] is not enabled:
        body = {"config": {"enabled": enabled}}
        try:
            (rc, response) = request(url=vcsa_url +
                                     "/appliance/local-accounts/%s" % account,
                                     url_username=vcsa_username,
                                     url_password=vcsa_password,
                                     validate_certs=validate_certs,
                                     headers=headers,
                                     data=bytes(json.dumps(body),
                                                encoding="utf-8"),
                                     method='PATCH')
        except:
            err = get_exception()
            module.fail_json(msg="Failed to enable %s. Error [%s]." %
                             (account, str(err)))
        changed.append('enabled')
        changed_status = True

    # check full name
    if full_name:
        if local_account['value']['fullname'] != full_name:
            body = {"config": {"full_name": full_name}}
            try:
                (rc, response) = request(
                    url=vcsa_url + "/appliance/local-accounts/%s" % account,
                    url_username=vcsa_username,
                    url_password=vcsa_password,
                    validate_certs=validate_certs,
                    headers=headers,
                    data=bytes(json.dumps(body), encoding="utf-8"),
                    method='PATCH')
            except:
                err = get_exception()
                module.fail_json(
                    msg="Failed to set full_name for %s. Error [%s]." %
                    (account, str(err)))
            changed.append('full_name')
            changed_status = True
    else:
        if local_account['value']['fullname'] != account:
            body = {"config": {"full_name": account}}
            try:
                (rc, response) = request(
                    url=vcsa_url + "/appliance/local-accounts/%s" % account,
                    url_username=vcsa_username,
                    url_password=vcsa_password,
                    validate_certs=validate_certs,
                    headers=headers,
                    data=bytes(json.dumps(body), encoding="utf-8"),
                    method='PATCH')
            except:
                err = get_exception()
                module.fail_json(
                    msg="Failed to set full_name for %s. Error [%s]." %
                    (account, str(err)))
            changed.append('full_name')
            changed_status = True

    # check password expiration
    if password_expires:
        # password expiration is disabled
        if local_account['value']['max_days_between_password_change'] in (
                99999, -1):
            body = {
                "config": {
                    "password_expires": password_expires,
                    "max_days_between_password_change": valid_days,
                    "email": email
                }
            }
            try:
                (rc, response) = request(
                    url=vcsa_url + "/appliance/local-accounts/%s" % account,
                    url_username=vcsa_username,
                    url_password=vcsa_password,
                    validate_certs=validate_certs,
                    headers=headers,
                    data=bytes(json.dumps(body), encoding="utf-8"),
                    method='PATCH')
            except:
                err = get_exception()
                module.fail_json(
                    msg=
                    "Failed to enable password expiration for %s. Error [%s]."
                    % (account, str(err)))
            changed.append('password_expires')
            changed_status = True
        else:
            if local_account['value'][
                    'max_days_between_password_change'] is not valid_days:
                body = {
                    "config": {
                        "max_days_between_password_change": valid_days
                    }
                }
                try:
                    (rc, response) = request(
                        url=vcsa_url +
                        "/appliance/local-accounts/%s" % account,
                        url_username=vcsa_username,
                        url_password=vcsa_password,
                        validate_certs=validate_certs,
                        headers=headers,
                        data=bytes(json.dumps(body), encoding="utf-8"),
                        method='PATCH')
                except:
                    err = get_exception()
                    module.fail_json(
                        msg="Failed to set valid_days for %s. Error [%s]." %
                        (account, str(err)))
                changed.append('valid_days')
                changed_status = True
            if local_account['value']['email'] != email:
                body = {"config": {"email": email}}
                try:
                    (rc, response) = request(
                        url=vcsa_url +
                        "/appliance/local-accounts/%s" % account,
                        url_username=vcsa_username,
                        url_password=vcsa_password,
                        validate_certs=validate_certs,
                        headers=headers,
                        data=bytes(json.dumps(body), encoding="utf-8"),
                        method='PATCH')
                except:
                    err = get_exception()
                    module.fail_json(
                        msg="Failed to set email for %s. Error [%s]." %
                        (account, str(err)))
                changed.append('email')
                changed_status = True
    else:
        # password expiration is not disabled
        if local_account['value']['max_days_between_password_change'] not in (
                99999, -1):
            body = {"config": {"password_expires": password_expires}}
            try:
                (rc, response) = request(
                    url=vcsa_url + "/appliance/local-accounts/%s" % account,
                    url_username=vcsa_username,
                    url_password=vcsa_password,
                    validate_certs=validate_certs,
                    headers=headers,
                    data=bytes(json.dumps(body), encoding="utf-8"),
                    method='PATCH')
            except:
                err = get_exception()
                module.fail_json(
                    msg=
                    "Failed to disable password expiration for %s. Error [%s]."
                    % (account, str(err)))
            changed.append('password_expires')
            changed_status = True

    if changed_status:
        if len(changed) > 2:
            message = ', '.join(changed[:-1]) + ', and ' + str(
                changed[-1]) + ' changed.'
        elif len(changed) == 2:
            message = ' and '.join(changed) + ' changed.'
        elif len(changed) == 1:
            message = changed[0] + ' changed.'
    else:
        message = 'all settings are already configured.'

    module.exit_json(changed=changed_status, msg=message)
コード例 #4
0
def configure_vcsa_update(module, vcsa_url, vcsa_username, vcsa_password,
                          auto_stage, day, hour, minute, url, validate_certs):
    """Configure vCSA update"""

    changed = []
    changed_status = False

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        (rc, session_id) = request(url=vcsa_url + "/com/vmware/cis/session",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers,
                                   method='POST')
    except:
        err = get_exception()
        module.fail_json(
            msg="Failed to establish a session and authenticate. Error [%s]." %
            str(err))

    headers.update({'vmware-api-session-id': session_id['value']})

    try:
        (rc,
         system_version) = request(url=vcsa_url + "/appliance/system/version",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get appliance version. Error [%s]." %
                         str(err))

    appliance_version = system_version['value']['version']
    if appliance_version.startswith('6.7'):
        try:
            (rc, system_update) = request(url=vcsa_url +
                                          "/appliance/update/policy",
                                          url_username=vcsa_username,
                                          url_password=vcsa_password,
                                          validate_certs=validate_certs,
                                          headers=headers)
        except:
            err = get_exception()
            module.fail_json(msg="Failed to get update policy. Error [%s]." %
                             str(err))
        body = {}
        body_policy = {}
        # check auto staging
        if system_update['value']['auto_stage'] is not auto_stage:
            body_policy['auto_stage'] = auto_stage
            changed.append('auto_stage')
            changed_status = True
        else:
            body_policy['auto_stage'] = system_update['value']['auto_stage']
        if auto_stage:
            # check automatic check schedule
            if not system_update['value']['check_schedule']:
                body_policy['check_schedule'] = [{
                    "day": day,
                    "hour": hour,
                    "minute": minute
                }]
                changed.append('check_schedule')
                changed_status = True
            else:
                schedule_changed = False
                if system_update['value']['check_schedule'][0]['day'] != day:
                    body_policy['check_schedule'] = [{
                        "day": day,
                        "hour": hour,
                        "minute": minute
                    }]
                    changed.append('check_schedule_day')
                    changed_status = True
                    schedule_changed = True
                if system_update['value']['check_schedule'][0][
                        'hour'] is not hour:
                    body_policy['check_schedule'] = [{
                        "day": day,
                        "hour": hour,
                        "minute": minute
                    }]
                    changed.append('check_schedule_hour')
                    changed_status = True
                    schedule_changed = True
                if system_update['value']['check_schedule'][0][
                        'minute'] is not minute:
                    body_policy['check_schedule'] = [{
                        "day": day,
                        "hour": hour,
                        "minute": minute
                    }]
                    changed.append('check_schedule_minute')
                    changed_status = True
                    schedule_changed = True
                if not schedule_changed:
                    body_policy['check_schedule'] = [{
                        "day": day,
                        "hour": hour,
                        "minute": minute
                    }]
            # check update URL
            if url:
                if 'custom_URL' in system_update['value']:
                    if system_update['value']['custom_URL'] != url:
                        body_policy['custom_URL'] = url
                        changed.append('url')
                        changed_status = True
                else:
                    body_policy['custom_URL'] = url
                    changed.append('url')
                    changed_status = True
            else:
                if 'custom_URL' in system_update['value']:
                    changed.append('url')
                    changed_status = True
        else:
            if system_update['value']['check_schedule']:
                body_policy['check_schedule'] = []
                changed.append('check_schedule')
                changed_status = True
            if 'custom_URL' in system_update['value']:
                changed.append('url')
                changed_status = True

        if changed_status:
            if module.check_mode:
                changed_message = ' would be changed.'
            else:
                body = {"policy": body_policy}
                try:
                    (rc, response) = request(
                        url=vcsa_url + "/appliance/update/policy",
                        url_username=vcsa_username,
                        url_password=vcsa_password,
                        validate_certs=validate_certs,
                        headers=headers,
                        data=bytes(json.dumps(body).encode("utf-8")),
                        method='PUT')
                except:
                    err = get_exception()
                    module.fail_json(
                        msg="Failed to set valid_days for %s. Error [%s]." %
                        (account, str(err)))
                changed_message = ' changed.'
            if len(changed) > 2:
                message = ', '.join(changed[:-1]) + ', and ' + str(
                    changed[-1]) + changed_message
            elif len(changed) == 2:
                message = ' and '.join(changed) + changed_message
            elif len(changed) == 1:
                message = changed[0] + changed_message
        else:
            message = 'all settings are already configured.'

        module.exit_json(changed=changed_status, msg=message)
    else:
        module.fail_json(msg="Appliance version %s not supported!" %
                         appliance_version)
コード例 #5
0
def check_vcsa_access(module, vcsa_url, vcsa_username, vcsa_password,
                      console_access, dcui_access, ssh_access, shell_access,
                      validate_certs):
    """Inform the user what would change if the module were run"""

    would_be_changed = []
    changed_status = False

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        (rc, session_id) = request(url=vcsa_url + "/com/vmware/cis/session",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers,
                                   method='POST')
    except:
        err = get_exception()
        module.fail_json(
            msg="Failed to establish a session and authenticate. Error [%s]." %
            str(err))

    headers.update({'vmware-api-session-id': session_id['value']})

    # console-based controlled CLI (TTY1) access
    try:
        (rc,
         consolecli) = request(url=vcsa_url + "/appliance/access/consolecli",
                               url_username=vcsa_username,
                               url_password=vcsa_password,
                               validate_certs=validate_certs,
                               headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get consolecli state. Error [%s]." %
                         str(err))

    if consolecli['value'] != console_access:
        would_be_changed.append('console')
        changed_status = True

    # Direct Console User Interface (DCUI TTY2) access
    try:
        (rc, dcui) = request(url=vcsa_url + "/appliance/access/dcui",
                             url_username=vcsa_username,
                             url_password=vcsa_password,
                             validate_certs=validate_certs,
                             headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get DCUI state. Error [%s]." %
                         str(err))

    if dcui['value'] != dcui_access:
        would_be_changed.append('dcui')
        changed_status = True

    # SSH-based controlled CLI access
    try:
        (rc, ssh) = request(url=vcsa_url + "/appliance/access/ssh",
                            url_username=vcsa_username,
                            url_password=vcsa_password,
                            validate_certs=validate_certs,
                            headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get SSH state. Error [%s]." % str(err))

    if ssh['value'] != ssh_access:
        would_be_changed.append('ssh')
        changed_status = True

    # access to BASH from within the controlled CLI
    try:
        (rc, shell) = request(url=vcsa_url + "/appliance/access/shell",
                              url_username=vcsa_username,
                              url_password=vcsa_password,
                              validate_certs=validate_certs,
                              headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get BASH shell state. Error [%s]." %
                         str(err))

    if shell['value']['enabled'] != shell_access:
        would_be_changed.append('shell')
        changed_status = True

    if changed_status:
        if len(would_be_changed) > 2:
            message = ', '.join(would_be_changed[:-1]) + ', and ' + str(
                would_be_changed[-1]) + ' would be changed.'
        elif len(would_be_changed) == 2:
            message = ' and '.join(would_be_changed) + ' would be changed.'
        elif len(would_be_changed) == 1:
            message = would_be_changed[0] + ' would be changed.'
    else:
        message = 'all settings are already configured.'

    module.exit_json(changed=changed_status, msg=message)
コード例 #6
0
def check_vmon_services(module, vcsa_url, vcsa_username, vcsa_password,
                        vcsa_services, vcsa_state, vcsa_startup_type,
                        validate_certs):
    """Inform the user what would change if the module were run"""

    would_be_changed_state = []
    would_be_changed_startup_type = []
    service_state_changed = False
    service_startup_type_changed = False

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        (rc, session_id) = request(url=vcsa_url + "/com/vmware/cis/session",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers,
                                   method='POST')
    except:
        err = get_exception()
        module.fail_json(
            msg="Failed to establish a session and authenticate. Error [%s]." %
            str(err))

    headers.update({'vmware-api-session-id': session_id['value']})
    try:
        (rc, vmon_services) = request(url=vcsa_url + "/appliance/vmon/service",
                                      url_username=vcsa_username,
                                      url_password=vcsa_password,
                                      validate_certs=validate_certs,
                                      headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get vmon services. Error [%s]." %
                         str(err))

    for vmon_service in vmon_services['value']:
        for vcsa_service in vcsa_services:
            if vmon_service['key'] == vcsa_service:
                if vcsa_state == 'restarted':
                    would_be_changed_state.append(vmon_service['key'])
                    service_state_changed = True
                else:
                    if (vmon_service['value']['state'].lower() != vcsa_state):
                        would_be_changed_state.append(vmon_service['key'])
                        service_state_changed = True
                if (vmon_service['value']['startup_type'].lower() !=
                        vcsa_startup_type):
                    would_be_changed_startup_type.append(vmon_service['key'])
                    service_startup_type_changed = True

    if service_state_changed or service_startup_type_changed:
        message_state = ''
        message_startup_type = ''
        if service_state_changed:
            changed_status = True
            if len(would_be_changed_state) > 2:
                message_state = 'Services '
                message_state = message_state + ', '.join(
                    would_be_changed_state[:-1]) + ', and ' + str(
                        would_be_changed_state[-1]
                    ) + ' would be %s.' % vcsa_state
            elif len(would_be_changed_state) == 2:
                message_state = 'Services '
                message_state = message_state + ' and '.join(
                    would_be_changed_state) + ' would be %s.' % vcsa_state
            elif len(would_be_changed_state) == 1:
                message_state = 'Service '
                message_state = message_state + would_be_changed_state[
                    0] + ' would be %s.' % vcsa_state
        if service_startup_type_changed:
            changed_status = True
            if len(would_be_changed_startup_type) > 2:
                message_startup_type = 'Services '
                message_startup_type = message_startup_type + ', '.join(
                    would_be_changed_startup_type[:-1]) + ', and ' + str(
                        would_be_changed_startup_type[-1]
                    ) + ' startup type would be set to %s.' % vcsa_startup_type
            elif len(would_be_changed_startup_type) == 2:
                message_startup_type = 'Services '
                message_startup_type = message_startup_type + ' and '.join(
                    would_be_changed_startup_type
                ) + ' startup type would be set to %s.' % vcsa_startup_type
            elif len(would_be_changed_startup_type) == 1:
                message_startup_type = 'Service '
                message_startup_type = message_startup_type + would_be_changed_startup_type[
                    0] + ' startup type would be set to %s.' % vcsa_startup_type
        if message_state != '':
            message = message_state
            if message_startup_type != '':
                message = message + " " + message_startup_type
        elif message_startup_type != '':
            message = message_startup_type
    else:
        changed_status = False
        message = 'Services already %s and startup type set to %s.' % (
            vcsa_state, vcsa_startup_type)

    module.exit_json(changed=changed_status, msg=message)
コード例 #7
0
def configure_vmon_services(module, vcsa_url, vcsa_username, vcsa_password,
                            vcsa_services, vcsa_state, vcsa_startup_type,
                            validate_certs):
    """Configure vCSA services"""

    changed_state = []
    changed_startup_type = []
    service_state_changed = False
    service_startup_type_changed = False

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        (rc, session_id) = request(url=vcsa_url + "/com/vmware/cis/session",
                                   url_username=vcsa_username,
                                   url_password=vcsa_password,
                                   validate_certs=validate_certs,
                                   headers=headers,
                                   method='POST')
    except:
        err = get_exception()
        module.fail_json(
            msg="Failed to establish a session and authenticate. Error [%s]." %
            str(err))

    headers.update({'vmware-api-session-id': session_id['value']})
    try:
        (rc, vmon_services) = request(url=vcsa_url + "/appliance/vmon/service",
                                      url_username=vcsa_username,
                                      url_password=vcsa_password,
                                      validate_certs=validate_certs,
                                      headers=headers)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to get vmon services. Error [%s]." %
                         str(err))

    for vmon_service in vmon_services['value']:
        for vcsa_service in vcsa_services:
            if vmon_service['key'] == vcsa_service:
                if vcsa_state == 'restarted':
                    try:
                        (rc, response) = request(
                            url=vcsa_url +
                            "/appliance/vmon/service/%s/restart" %
                            vmon_service['key'],
                            url_username=vcsa_username,
                            url_password=vcsa_password,
                            validate_certs=validate_certs,
                            headers=headers,
                            method='POST')
                    except:
                        err = get_exception()
                        module.fail_json(
                            msg="Failed to restart %s. Error [%s]." %
                            (vmon_service['key'], str(err)))
                    service_state_changed = True
                    changed_state.append(vmon_service['key'])
                else:
                    if (vmon_service['value']['state'].lower() != vcsa_state):
                        if vcsa_state == 'started':
                            type = "start"
                        else:
                            type = "stop"
                        try:
                            (rc, response) = request(
                                url=vcsa_url +
                                "/appliance/vmon/service/%s/%s" %
                                (vmon_service['key'], type),
                                url_username=vcsa_username,
                                url_password=vcsa_password,
                                validate_certs=validate_certs,
                                headers=headers,
                                method='POST')
                        except:
                            err = get_exception()
                            module.fail_json(
                                msg="Failed to %s service %s. Error [%s]." %
                                (type, vmon_service['key'], str(err)))
                        service_state_changed = True
                        changed_state.append(vmon_service['key'])
                    if (vmon_service['value']['startup_type'].lower() !=
                            vcsa_startup_type):
                        body = {
                            "spec": {
                                "startup_type": vcsa_startup_type.upper()
                            }
                        }
                        try:
                            (rc, response) = request(
                                url=vcsa_url + "/appliance/vmon/service/%s" %
                                vmon_service['key'],
                                url_username=vcsa_username,
                                url_password=vcsa_password,
                                validate_certs=validate_certs,
                                headers=headers,
                                data=bytes(json.dumps(body).encode("utf-8")),
                                method='PATCH')
                        except:
                            err = get_exception()
                            module.fail_json(
                                msg=
                                "Failed to set startup type to '%s' for service '%s'. Error [%s]."
                                % (vcsa_startup_type, vcsa_service, str(err)))
                        service_startup_type_changed = True
                        changed_startup_type.append(vmon_service['key'])

    if service_state_changed or service_startup_type_changed:
        message_state = ''
        message_startup_type = ''
        if service_state_changed:
            changed_status = True
            if len(changed_state) > 2:
                message_state = 'Services '
                message_state = message_state + ', '.join(
                    changed_state[:-1]) + ', and ' + str(
                        changed_state[-1]) + ' %s.' % vcsa_state
            elif len(changed_state) == 2:
                message_state = 'Services '
                message_state = message_state + ' and '.join(
                    changed_state) + ' %s.' % vcsa_state
            elif len(changed_state) == 1:
                message_state = 'Service '
                message_state = message_state + changed_state[
                    0] + ' %s.' % vcsa_state
        if service_startup_type_changed:
            changed_status = True
            if len(changed_startup_type) > 2:
                message_startup_type = 'Services '
                message_startup_type = message_startup_type + ', '.join(
                    changed_startup_type[:-1]) + ', and ' + str(
                        changed_startup_type[-1]
                    ) + ' startup type set to %s.' % vcsa_startup_type
            elif len(changed_startup_type) == 2:
                message_startup_type = 'Services '
                message_startup_type = message_startup_type + ' and '.join(
                    changed_startup_type
                ) + ' startup type set to %s.' % vcsa_startup_type
            elif len(changed_startup_type) == 1:
                message_startup_type = 'Service '
                message_startup_type = message_startup_type + changed_startup_type[
                    0] + ' startup type set to %s.' % vcsa_startup_type
        if message_state != '':
            message = message_state
            if message_startup_type != '':
                message = message + " " + message_startup_type
        elif message_startup_type != '':
            message = message_startup_type
    else:
        changed_status = False
        message = 'Services already %s and startup type set to %s.' % (
            vcsa_state, vcsa_startup_type)

    module.exit_json(changed=changed_status, msg=message)