status
stringclasses
1 value
repo_name
stringclasses
31 values
repo_url
stringclasses
31 values
issue_id
int64
1
104k
title
stringlengths
4
369
body
stringlengths
0
254k
issue_url
stringlengths
37
56
pull_url
stringlengths
37
54
before_fix_sha
stringlengths
40
40
after_fix_sha
stringlengths
40
40
report_datetime
timestamp[us, tz=UTC]
language
stringclasses
5 values
commit_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
4
188
file_content
stringlengths
0
5.12M
closed
ansible/ansible
https://github.com/ansible/ansible
61,895
gitlab_hook contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_hook contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_hook.py:302:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_hook.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61895
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:17Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_project.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_project short_description: Creates/updates/deletes GitLab Projects description: - When the project does not exist in GitLab, it will be created. - When the project does exists and state=absent, the project will be deleted. - When changes are made to the project, the project will be updated. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token group: description: - Id or The full path of the group of which this projects belongs to. type: str name: description: - The name of the project required: true type: str path: description: - The path of the project you want to create, this will be server_url/<group>/path - If not supplied, name will be used. type: str description: description: - An description for the project. type: str issues_enabled: description: - Whether you want to create issues or not. - Possible values are true and false. type: bool default: yes merge_requests_enabled: description: - If merge requests can be made or not. - Possible values are true and false. type: bool default: yes wiki_enabled: description: - If an wiki for this project should be available or not. - Possible values are true and false. type: bool default: yes snippets_enabled: description: - If creating snippets should be available or not. - Possible values are true and false. type: bool default: yes visibility: description: - Private. Project access must be granted explicitly for each user. - Internal. The project can be cloned by any logged in user. - Public. The project can be cloned without any authentication. default: private type: str choices: ["private", "internal", "public"] aliases: - visibility_level import_url: description: - Git repository which will be imported into gitlab. - GitLab server needs read access to this git repository. required: false type: str state: description: - create or delete project. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] ''' EXAMPLES = ''' - name: Delete GitLab Project gitlab_project: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False name: my_first_project state: absent delegate_to: localhost - name: Create GitLab Project in group Ansible gitlab_project: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: my_first_project group: ansible issues_enabled: False wiki_enabled: True snippets_enabled: True import_url: http://git.example.com/example/lab.git state: present delegate_to: localhost ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" project: description: API object returned: always type: dict ''' import os import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup, findProject class GitLabProject(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.projectObject = None ''' @param project_name Name of the project @param namespace Namespace Object (User or Group) @param options Options of the project ''' def createOrUpdateProject(self, project_name, namespace, options): changed = False # Because we have already call userExists in main() if self.projectObject is None: project = self.createProject(namespace, { 'name': project_name, 'path': options['path'], 'description': options['description'], 'issues_enabled': options['issues_enabled'], 'merge_requests_enabled': options['merge_requests_enabled'], 'wiki_enabled': options['wiki_enabled'], 'snippets_enabled': options['snippets_enabled'], 'visibility': options['visibility'], 'import_url': options['import_url']}) changed = True else: changed, project = self.updateProject(self.projectObject, { 'name': project_name, 'description': options['description'], 'issues_enabled': options['issues_enabled'], 'merge_requests_enabled': options['merge_requests_enabled'], 'wiki_enabled': options['wiki_enabled'], 'snippets_enabled': options['snippets_enabled'], 'visibility': options['visibility']}) self.projectObject = project if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name) try: project.save() except Exception as e: self._module.fail_json(msg="Failed update project: %s " % e) return True else: return False ''' @param namespace Namespace Object (User or Group) @param arguments Attributs of the project ''' def createProject(self, namespace, arguments): if self._module.check_mode: return True arguments['namespace_id'] = namespace.id try: project = self._gitlab.projects.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create project: %s " % to_native(e)) return project ''' @param project Project Object @param arguments Attributs of the project ''' def updateProject(self, project, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(project, arg_key) != arguments[arg_key]: setattr(project, arg_key, arguments[arg_key]) changed = True return (changed, project) def deleteProject(self): if self._module.check_mode: return True project = self.projectObject return project.delete() ''' @param namespace User/Group object @param name Name of the project ''' def existsProject(self, namespace, path): # When project exists, object will be stored in self.projectObject. project = findProject(self._gitlab, namespace.full_path + '/' + path) if project: self.projectObject = project return True return False def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), group=dict(type='str'), name=dict(type='str', required=True), path=dict(type='str'), description=dict(type='str'), issues_enabled=dict(type='bool', default=True), merge_requests_enabled=dict(type='bool', default=True), wiki_enabled=dict(type='bool', default=True), snippets_enabled=dict(default=True, type='bool'), visibility=dict(type='str', default="private", choices=["internal", "private", "public"], aliases=["visibility_level"]), import_url=dict(type='str'), state=dict(type='str', default="present", choices=["absent", "present"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] group_identifier = module.params['group'] project_name = module.params['name'] project_path = module.params['path'] project_description = module.params['description'] issues_enabled = module.params['issues_enabled'] merge_requests_enabled = module.params['merge_requests_enabled'] wiki_enabled = module.params['wiki_enabled'] snippets_enabled = module.params['snippets_enabled'] visibility = module.params['visibility'] import_url = module.params['import_url'] state = module.params['state'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) # Set project_path to project_name if it is empty. if project_path is None: project_path = project_name.replace(" ", "_") gitlab_project = GitLabProject(module, gitlab_instance) if group_identifier: group = findGroup(gitlab_instance, group_identifier) if group is None: module.fail_json(msg="Failed to create project: group %s doesn't exists" % group_identifier) namespace = gitlab_instance.namespaces.get(group.id) project_exists = gitlab_project.existsProject(namespace, project_path) else: user = gitlab_instance.users.list(username=gitlab_instance.user.username)[0] namespace = gitlab_instance.namespaces.get(user.id) project_exists = gitlab_project.existsProject(namespace, project_path) if state == 'absent': if project_exists: gitlab_project.deleteProject() module.exit_json(changed=True, msg="Successfully deleted project %s" % project_name) else: module.exit_json(changed=False, msg="Project deleted or does not exists") if state == 'present': if gitlab_project.createOrUpdateProject(project_name, namespace, { "path": project_path, "description": project_description, "issues_enabled": issues_enabled, "merge_requests_enabled": merge_requests_enabled, "wiki_enabled": wiki_enabled, "snippets_enabled": snippets_enabled, "visibility": visibility, "import_url": import_url}): module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name, project=gitlab_project.projectObject._attrs) else: module.exit_json(changed=False, msg="No need to update the project %s" % project_name, project=gitlab_project.projectObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,895
gitlab_hook contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_hook contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_hook.py:302:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_hook.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61895
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:17Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_runner.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2018, Samy Coenen <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_runner short_description: Create, modify and delete GitLab Runners. description: - Register, update and delete runners with the GitLab API. - All operations are performed using the GitLab API v4. - For details, consult the full API documentation at U(https://docs.gitlab.com/ee/api/runners.html). - A valid private API token is required for all operations. You can create as many tokens as you like using the GitLab web interface at U(https://$GITLAB_URL/profile/personal_access_tokens). - A valid registration token is required for registering a new runner. To create shared runners, you need to ask your administrator to give you this token. It can be found at U(https://$GITLAB_URL/admin/runners/). notes: - To create a new runner at least the C(api_token), C(description) and C(url) options are required. - Runners need to have unique descriptions. version_added: 2.8 author: - Samy Coenen (@SamyCoenen) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab >= 1.5.0 extends_documentation_fragment: - auth_basic options: url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str api_token: description: - Your private token to interact with the GitLab API. required: True type: str aliases: - private_token description: description: - The unique name of the runner. required: True type: str aliases: - name state: description: - Make sure that the runner with the same name exists with the same configuration or delete the runner with the same name. required: False default: present choices: ["present", "absent"] type: str registration_token: description: - The registration token is used to register new runners. required: True type: str active: description: - Define if the runners is immediately active after creation. required: False default: yes type: bool locked: description: - Determines if the runner is locked or not. required: False default: False type: bool access_level: description: - Determines if a runner can pick up jobs from protected branches. required: False default: ref_protected choices: ["ref_protected", "not_protected"] type: str maximum_timeout: description: - The maximum timeout that a runner has to pick up a specific job. required: False default: 3600 type: int run_untagged: description: - Run untagged jobs or not. required: False default: yes type: bool tag_list: description: The tags that apply to the runner. required: False default: [] type: list ''' EXAMPLES = ''' - name: "Register runner" gitlab_runner: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" registration_token: 4gfdsg345 description: Docker Machine t1 state: present active: True tag_list: ['docker'] run_untagged: False locked: False - name: "Delete runner" gitlab_runner: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" description: Docker Machine t1 state: absent ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" runner: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native try: cmp except NameError: def cmp(a, b): return (a > b) - (a < b) class GitLabRunner(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.runnerObject = None def createOrUpdateRunner(self, description, options): changed = False # Because we have already call userExists in main() if self.runnerObject is None: runner = self.createRunner({ 'description': description, 'active': options['active'], 'token': options['registration_token'], 'locked': options['locked'], 'run_untagged': options['run_untagged'], 'maximum_timeout': options['maximum_timeout'], 'tag_list': options['tag_list']}) changed = True else: changed, runner = self.updateRunner(self.runnerObject, { 'active': options['active'], 'locked': options['locked'], 'run_untagged': options['run_untagged'], 'maximum_timeout': options['maximum_timeout'], 'access_level': options['access_level'], 'tag_list': options['tag_list']}) self.runnerObject = runner if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the runner %s" % description) try: runner.save() except Exception as e: self._module.fail_json(msg="Failed to update runner: %s " % to_native(e)) return True else: return False ''' @param arguments Attributs of the runner ''' def createRunner(self, arguments): if self._module.check_mode: return True try: runner = self._gitlab.runners.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create runner: %s " % to_native(e)) return runner ''' @param runner Runner object @param arguments Attributs of the runner ''' def updateRunner(self, runner, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if isinstance(arguments[arg_key], list): list1 = getattr(runner, arg_key) list1.sort() list2 = arguments[arg_key] list2.sort() if cmp(list1, list2): setattr(runner, arg_key, arguments[arg_key]) changed = True else: if getattr(runner, arg_key) != arguments[arg_key]: setattr(runner, arg_key, arguments[arg_key]) changed = True return (changed, runner) ''' @param description Description of the runner ''' def findRunner(self, description): runners = self._gitlab.runners.list(as_list=False) for runner in runners: if (runner.description == description): return self._gitlab.runners.get(runner.id) ''' @param description Description of the runner ''' def existsRunner(self, description): # When runner exists, object will be stored in self.runnerObject. runner = self.findRunner(description) if runner: self.runnerObject = runner return True return False def deleteRunner(self): if self._module.check_mode: return True runner = self.runnerObject return runner.delete() def deprecation_warning(module): deprecated_aliases = ['private_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( url=dict(type='str', removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["private_token"]), description=dict(type='str', required=True, aliases=["name"]), active=dict(type='bool', default=True), tag_list=dict(type='list', default=[]), run_untagged=dict(type='bool', default=True), locked=dict(type='bool', default=False), access_level=dict(type='str', default='ref_protected', choices=["not_protected", "ref_protected"]), maximum_timeout=dict(type='int', default=3600), registration_token=dict(type='str', required=True), state=dict(type='str', default="present", choices=["absent", "present"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'url'], ['api_username', 'api_token'], ['api_password', 'api_token'], ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token'], ['api_url', 'url'] ], supports_check_mode=True, ) deprecation_warning(module) if module.params['url'] is not None: url = re.sub('/api.*', '', module.params['url']) api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] gitlab_url = url if api_url is None else api_url gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] state = module.params['state'] runner_description = module.params['description'] runner_active = module.params['active'] tag_list = module.params['tag_list'] run_untagged = module.params['run_untagged'] runner_locked = module.params['locked'] access_level = module.params['access_level'] maximum_timeout = module.params['maximum_timeout'] registration_token = module.params['registration_token'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2" % to_native(e)) gitlab_runner = GitLabRunner(module, gitlab_instance) runner_exists = gitlab_runner.existsRunner(runner_description) if state == 'absent': if runner_exists: gitlab_runner.deleteRunner() module.exit_json(changed=True, msg="Successfully deleted runner %s" % runner_description) else: module.exit_json(changed=False, msg="Runner deleted or does not exists") if state == 'present': if gitlab_runner.createOrUpdateRunner(runner_description, { "active": runner_active, "tag_list": tag_list, "run_untagged": run_untagged, "locked": runner_locked, "access_level": access_level, "maximum_timeout": maximum_timeout, "registration_token": registration_token}): module.exit_json(changed=True, runner=gitlab_runner.runnerObject._attrs, msg="Successfully created or updated the runner %s" % runner_description) else: module.exit_json(changed=False, runner=gitlab_runner.runnerObject._attrs, msg="No need to update the runner %s" % runner_description) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,895
gitlab_hook contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_hook contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_hook.py:302:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_hook.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61895
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:17Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_user.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_user short_description: Creates/updates/deletes GitLab Users description: - When the user does not exist in GitLab, it will be created. - When the user does exists and state=absent, the user will be deleted. - When changes are made to user, the user will be updated. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module - administrator rights on the GitLab server extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token name: description: - Name of the user you want to create required: true type: str username: description: - The username of the user. required: true type: str password: description: - The password of the user. - GitLab server enforces minimum password length to 8, set this value with 8 or more characters. required: true type: str email: description: - The email that belongs to the user. required: true type: str sshkey_name: description: - The name of the sshkey type: str sshkey_file: description: - The ssh key itself. type: str group: description: - Id or Full path of parent group in the form of group/name - Add user as an member to this group. type: str access_level: description: - The access level to the group. One of the following can be used. - guest - reporter - developer - master (alias for maintainer) - maintainer - owner default: guest type: str choices: ["guest", "reporter", "developer", "master", "maintainer", "owner"] state: description: - create or delete group. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] confirm: description: - Require confirmation. type: bool default: yes version_added: "2.4" isadmin: description: - Grant admin privileges to the user type: bool default: no version_added: "2.8" external: description: - Define external parameter for this user type: bool default: no version_added: "2.8" ''' EXAMPLES = ''' - name: "Delete GitLab User" gitlab_user: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False username: myusername state: absent delegate_to: localhost - name: "Create GitLab User" gitlab_user: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: My Name username: myusername password: mysecretpassword email: [email protected] sshkey_name: MySSH sshkey_file: ssh-rsa AAAAB3NzaC1yc... state: present group: super_group/mon_group access_level: owner delegate_to: localhost ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" user: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup class GitLabUser(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.userObject = None self.ACCESS_LEVEL = { 'guest': gitlab.GUEST_ACCESS, 'reporter': gitlab.REPORTER_ACCESS, 'developer': gitlab.DEVELOPER_ACCESS, 'master': gitlab.MAINTAINER_ACCESS, 'maintainer': gitlab.MAINTAINER_ACCESS, 'owner': gitlab.OWNER_ACCESS} ''' @param username Username of the user @param options User options ''' def createOrUpdateUser(self, username, options): changed = False # Because we have already call userExists in main() if self.userObject is None: user = self.createUser({ 'name': options['name'], 'username': username, 'password': options['password'], 'email': options['email'], 'skip_confirmation': not options['confirm'], 'admin': options['isadmin'], 'external': options['external']}) changed = True else: changed, user = self.updateUser(self.userObject, { 'name': options['name'], 'email': options['email'], 'is_admin': options['isadmin'], 'external': options['external']}) # Assign ssh keys if options['sshkey_name'] and options['sshkey_file']: key_changed = self.addSshKeyToUser(user, { 'name': options['sshkey_name'], 'file': options['sshkey_file']}) changed = changed or key_changed # Assign group if options['group_path']: group_changed = self.assignUserToGroup(user, options['group_path'], options['access_level']) changed = changed or group_changed self.userObject = user if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the user %s" % username) try: user.save() except Exception as e: self._module.fail_json(msg="Failed to update user: %s " % to_native(e)) return True else: return False ''' @param group User object ''' def getUserId(self, user): if user is not None: return user.id return None ''' @param user User object @param sshkey_name Name of the ssh key ''' def sshKeyExists(self, user, sshkey_name): keyList = map(lambda k: k.title, user.keys.list()) return sshkey_name in keyList ''' @param user User object @param sshkey Dict containing sshkey infos {"name": "", "file": ""} ''' def addSshKeyToUser(self, user, sshkey): if not self.sshKeyExists(user, sshkey['name']): if self._module.check_mode: return True try: user.keys.create({ 'title': sshkey['name'], 'key': sshkey['file']}) except gitlab.exceptions.GitlabCreateError as e: self._module.fail_json(msg="Failed to assign sshkey to user: %s" % to_native(e)) return True return False ''' @param group Group object @param user_id Id of the user to find ''' def findMember(self, group, user_id): try: member = group.members.get(user_id) except gitlab.exceptions.GitlabGetError as e: return None return member ''' @param group Group object @param user_id Id of the user to check ''' def memberExists(self, group, user_id): member = self.findMember(group, user_id) return member is not None ''' @param group Group object @param user_id Id of the user to check @param access_level GitLab access_level to check ''' def memberAsGoodAccessLevel(self, group, user_id, access_level): member = self.findMember(group, user_id) return member.access_level == access_level ''' @param user User object @param group_path Complete path of the Group including parent group path. <parent_path>/<group_path> @param access_level GitLab access_level to assign ''' def assignUserToGroup(self, user, group_identifier, access_level): group = findGroup(self._gitlab, group_identifier) if self._module.check_mode: return True if group is None: return False if self.memberExists(group, self.getUserId(user)): member = self.findMember(group, self.getUserId(user)) if not self.memberAsGoodAccessLevel(group, member.id, self.ACCESS_LEVEL[access_level]): member.access_level = self.ACCESS_LEVEL[access_level] member.save() return True else: try: group.members.create({ 'user_id': self.getUserId(user), 'access_level': self.ACCESS_LEVEL[access_level]}) except gitlab.exceptions.GitlabCreateError as e: self._module.fail_json(msg="Failed to assign user to group: %s" % to_native(e)) return True return False ''' @param user User object @param arguments User attributes ''' def updateUser(self, user, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(user, arg_key) != arguments[arg_key]: setattr(user, arg_key, arguments[arg_key]) changed = True return (changed, user) ''' @param arguments User attributes ''' def createUser(self, arguments): if self._module.check_mode: return True try: user = self._gitlab.users.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create user: %s " % to_native(e)) return user ''' @param username Username of the user ''' def findUser(self, username): users = self._gitlab.users.list(search=username) for user in users: if (user.username == username): return user ''' @param username Username of the user ''' def existsUser(self, username): # When user exists, object will be stored in self.userObject. user = self.findUser(username) if user: self.userObject = user return True return False def deleteUser(self): if self._module.check_mode: return True user = self.userObject return user.delete() def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), name=dict(type='str', required=True), state=dict(type='str', default="present", choices=["absent", "present"]), username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), email=dict(type='str', required=True), sshkey_name=dict(type='str'), sshkey_file=dict(type='str'), group=dict(type='str'), access_level=dict(type='str', default="guest", choices=["developer", "guest", "maintainer", "master", "owner", "reporter"]), confirm=dict(type='bool', default=True), isadmin=dict(type='bool', default=False), external=dict(type='bool', default=False), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] user_name = module.params['name'] state = module.params['state'] user_username = module.params['username'].lower() user_password = module.params['password'] user_email = module.params['email'] user_sshkey_name = module.params['sshkey_name'] user_sshkey_file = module.params['sshkey_file'] group_path = module.params['group'] access_level = module.params['access_level'] confirm = module.params['confirm'] user_isadmin = module.params['isadmin'] user_external = module.params['external'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) gitlab_user = GitLabUser(module, gitlab_instance) user_exists = gitlab_user.existsUser(user_username) if state == 'absent': if user_exists: gitlab_user.deleteUser() module.exit_json(changed=True, msg="Successfully deleted user %s" % user_username) else: module.exit_json(changed=False, msg="User deleted or does not exists") if state == 'present': if gitlab_user.createOrUpdateUser(user_username, { "name": user_name, "password": user_password, "email": user_email, "sshkey_name": user_sshkey_name, "sshkey_file": user_sshkey_file, "group_path": group_path, "access_level": access_level, "confirm": confirm, "isadmin": user_isadmin, "external": user_external}): module.exit_json(changed=True, msg="Successfully created or updated the user %s" % user_username, user=gitlab_user.userObject._attrs) else: module.exit_json(changed=False, msg="No need to update the user %s" % user_username, user=gitlab_user.userObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,894
gitlab_group contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_group contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_group.py:273:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_group.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61894
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:16Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_deploy_key.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2018, Marcus Watkins <[email protected]> # Based on code: # Copyright: (c) 2013, Phillip Gentry <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: gitlab_deploy_key short_description: Manages GitLab project deploy keys. description: - Adds, updates and removes project deploy keys version_added: "2.6" author: - Marcus Watkins (@marwatk) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: api_token: description: - GitLab token for logging in. version_added: "2.8" type: str aliases: - private_token - access_token project: description: - Id or Full path of project in the form of group/name required: true type: str title: description: - Deploy key's title required: true type: str key: description: - Deploy key required: true type: str can_push: description: - Whether this key can push to the project type: bool default: no state: description: - When C(present) the deploy key added to the project if it doesn't exist. - When C(absent) it will be removed from the project if it exists required: true default: present type: str choices: [ "present", "absent" ] ''' EXAMPLES = ''' - name: "Adding a project deploy key" gitlab_deploy_key: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" title: "Jenkins CI" state: present key: "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt4596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9w..." - name: "Update the above deploy key to add push access" gitlab_deploy_key: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" title: "Jenkins CI" state: present can_push: yes - name: "Remove the previous deploy key from the project" gitlab_deploy_key: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" state: absent key: "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt4596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9w..." ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: key is already in use" deploy_key: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findProject class GitLabDeployKey(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.deployKeyObject = None ''' @param project Project object @param key_title Title of the key @param key_key String of the key @param key_can_push Option of the deployKey @param options Deploy key options ''' def createOrUpdateDeployKey(self, project, key_title, key_key, options): changed = False # Because we have already call existsDeployKey in main() if self.deployKeyObject is None: deployKey = self.createDeployKey(project, { 'title': key_title, 'key': key_key, 'can_push': options['can_push']}) changed = True else: changed, deployKey = self.updateDeployKey(self.deployKeyObject, { 'can_push': options['can_push']}) self.deployKeyObject = deployKey if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title) try: deployKey.save() except Exception as e: self._module.fail_json(msg="Failed to update deploy key: %s " % e) return True else: return False ''' @param project Project Object @param arguments Attributs of the deployKey ''' def createDeployKey(self, project, arguments): if self._module.check_mode: return True try: deployKey = project.keys.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create deploy key: %s " % to_native(e)) return deployKey ''' @param deployKey Deploy Key Object @param arguments Attributs of the deployKey ''' def updateDeployKey(self, deployKey, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(deployKey, arg_key) != arguments[arg_key]: setattr(deployKey, arg_key, arguments[arg_key]) changed = True return (changed, deployKey) ''' @param project Project object @param key_title Title of the key ''' def findDeployKey(self, project, key_title): deployKeys = project.keys.list() for deployKey in deployKeys: if (deployKey.title == key_title): return deployKey ''' @param project Project object @param key_title Title of the key ''' def existsDeployKey(self, project, key_title): # When project exists, object will be stored in self.projectObject. deployKey = self.findDeployKey(project, key_title) if deployKey: self.deployKeyObject = deployKey return True return False def deleteDeployKey(self): if self._module.check_mode: return True return self.deployKeyObject.delete() def deprecation_warning(module): deprecated_aliases = ['private_token', 'access_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_token=dict(type='str', no_log=True, aliases=["private_token", "access_token"]), state=dict(type='str', default="present", choices=["absent", "present"]), project=dict(type='str', required=True), key=dict(type='str', required=True), can_push=dict(type='bool', default=False), title=dict(type='str', required=True) )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_username', 'api_token'], ['api_password', 'api_token'] ], required_together=[ ['api_username', 'api_password'] ], required_one_of=[ ['api_username', 'api_token'] ], supports_check_mode=True, ) deprecation_warning(module) gitlab_url = re.sub('/api.*', '', module.params['api_url']) validate_certs = module.params['validate_certs'] gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] state = module.params['state'] project_identifier = module.params['project'] key_title = module.params['title'] key_keyfile = module.params['key'] key_can_push = module.params['can_push'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) gitlab_deploy_key = GitLabDeployKey(module, gitlab_instance) project = findProject(gitlab_instance, project_identifier) if project is None: module.fail_json(msg="Failed to create deploy key: project %s doesn't exists" % project_identifier) deployKey_exists = gitlab_deploy_key.existsDeployKey(project, key_title) if state == 'absent': if deployKey_exists: gitlab_deploy_key.deleteDeployKey() module.exit_json(changed=True, msg="Successfully deleted deploy key %s" % key_title) else: module.exit_json(changed=False, msg="Deploy key deleted or does not exists") if state == 'present': if gitlab_deploy_key.createOrUpdateDeployKey(project, key_title, key_keyfile, {'can_push': key_can_push}): module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title, deploy_key=gitlab_deploy_key.deployKeyObject._attrs) else: module.exit_json(changed=False, msg="No need to update the deploy key %s" % key_title, deploy_key=gitlab_deploy_key.deployKeyObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,894
gitlab_group contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_group contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_group.py:273:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_group.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61894
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:16Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_group.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_group short_description: Creates/updates/deletes GitLab Groups description: - When the group does not exist in GitLab, it will be created. - When the group does exist and state=absent, the group will be deleted. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token name: description: - Name of the group you want to create. required: true type: str path: description: - The path of the group you want to create, this will be server_url/group_path - If not supplied, the group_name will be used. type: str description: description: - A description for the group. version_added: "2.7" type: str state: description: - create or delete group. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] parent: description: - Allow to create subgroups - Id or Full path of parent group in the form of group/name version_added: "2.8" type: str visibility: description: - Default visibility of the group version_added: "2.8" choices: ["private", "internal", "public"] default: private type: str ''' EXAMPLES = ''' - name: "Delete GitLab Group" gitlab_group: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False name: my_first_group state: absent - name: "Create GitLab Group" gitlab_group: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: my_first_group path: my_first_group state: present # The group will by created at https://gitlab.dj-wasabi.local/super_parent/parent/my_first_group - name: "Create GitLab SubGroup" gitlab_group: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: my_first_group path: my_first_group state: present parent: "super_parent/parent" ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" group: description: API object returned: always type: dict ''' import os import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup class GitLabGroup(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.groupObject = None ''' @param group Group object ''' def getGroupId(self, group): if group is not None: return group.id return None ''' @param name Name of the group @param parent Parent group full path @param options Group options ''' def createOrUpdateGroup(self, name, parent, options): changed = False # Because we have already call userExists in main() if self.groupObject is None: parent_id = self.getGroupId(parent) group = self.createGroup({ 'name': name, 'path': options['path'], 'parent_id': parent_id, 'visibility': options['visibility']}) changed = True else: changed, group = self.updateGroup(self.groupObject, { 'name': name, 'description': options['description'], 'visibility': options['visibility']}) self.groupObject = group if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the group %s" % name) try: group.save() except Exception as e: self._module.fail_json(msg="Failed to update group: %s " % e) return True else: return False ''' @param arguments Attributs of the group ''' def createGroup(self, arguments): if self._module.check_mode: return True try: group = self._gitlab.groups.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create group: %s " % to_native(e)) return group ''' @param group Group Object @param arguments Attributs of the group ''' def updateGroup(self, group, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(group, arg_key) != arguments[arg_key]: setattr(group, arg_key, arguments[arg_key]) changed = True return (changed, group) def deleteGroup(self): group = self.groupObject if len(group.projects.list()) >= 1: self._module.fail_json( msg="There are still projects in this group. These needs to be moved or deleted before this group can be removed.") else: if self._module.check_mode: return True try: group.delete() except Exception as e: self._module.fail_json(msg="Failed to delete group: %s " % to_native(e)) ''' @param name Name of the groupe @param full_path Complete path of the Group including parent group path. <parent_path>/<group_path> ''' def existsGroup(self, project_identifier): # When group/user exists, object will be stored in self.groupObject. group = findGroup(self._gitlab, project_identifier) if group: self.groupObject = group return True return False def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), name=dict(type='str', required=True), path=dict(type='str'), description=dict(type='str'), state=dict(type='str', default="present", choices=["absent", "present"]), parent=dict(type='str'), visibility=dict(type='str', default="private", choices=["internal", "private", "public"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] group_name = module.params['name'] group_path = module.params['path'] description = module.params['description'] state = module.params['state'] parent_identifier = module.params['parent'] group_visibility = module.params['visibility'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2" % to_native(e)) # Define default group_path based on group_name if group_path is None: group_path = group_name.replace(" ", "_") gitlab_group = GitLabGroup(module, gitlab_instance) parent_group = None if parent_identifier: parent_group = findGroup(gitlab_instance, parent_identifier) if not parent_group: module.fail_json(msg="Failed create GitLab group: Parent group doesn't exists") group_exists = gitlab_group.existsGroup(parent_group.full_path + '/' + group_path) else: group_exists = gitlab_group.existsGroup(group_path) if state == 'absent': if group_exists: gitlab_group.deleteGroup() module.exit_json(changed=True, msg="Successfully deleted group %s" % group_name) else: module.exit_json(changed=False, msg="Group deleted or does not exists") if state == 'present': if gitlab_group.createOrUpdateGroup(group_name, parent_group, { "path": group_path, "description": description, "visibility": group_visibility}): module.exit_json(changed=True, msg="Successfully created or updated the group %s" % group_name, group=gitlab_group.groupObject._attrs) else: module.exit_json(changed=False, msg="No need to update the group %s" % group_name, group=gitlab_group.groupObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,894
gitlab_group contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_group contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_group.py:273:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_group.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61894
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:16Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_hook.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2018, Marcus Watkins <[email protected]> # Based on code: # Copyright: (c) 2013, Phillip Gentry <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_hook short_description: Manages GitLab project hooks. description: - Adds, updates and removes project hook version_added: "2.6" author: - Marcus Watkins (@marwatk) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: api_token: description: - GitLab token for logging in. version_added: "2.8" type: str aliases: - private_token - access_token project: description: - Id or Full path of the project in the form of group/name. required: true type: str hook_url: description: - The url that you want GitLab to post to, this is used as the primary key for updates and deletion. required: true type: str state: description: - When C(present) the hook will be updated to match the input or created if it doesn't exist. - When C(absent) hook will be deleted if it exists. required: true default: present type: str choices: [ "present", "absent" ] push_events: description: - Trigger hook on push events. type: bool default: yes issues_events: description: - Trigger hook on issues events. type: bool default: no merge_requests_events: description: - Trigger hook on merge requests events. type: bool default: no tag_push_events: description: - Trigger hook on tag push events. type: bool default: no note_events: description: - Trigger hook on note events or when someone adds a comment. type: bool default: no job_events: description: - Trigger hook on job events. type: bool default: no pipeline_events: description: - Trigger hook on pipeline events. type: bool default: no wiki_page_events: description: - Trigger hook on wiki events. type: bool default: no hook_validate_certs: description: - Whether GitLab will do SSL verification when triggering the hook. type: bool default: no aliases: [ enable_ssl_verification ] token: description: - Secret token to validate hook messages at the receiver. - If this is present it will always result in a change as it cannot be retrieved from GitLab. - Will show up in the X-GitLab-Token HTTP request header. required: false type: str ''' EXAMPLES = ''' - name: "Adding a project hook" gitlab_hook: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" hook_url: "https://my-ci-server.example.com/gitlab-hook" state: present push_events: yes tag_push_events: yes hook_validate_certs: no token: "my-super-secret-token-that-my-ci-server-will-check" - name: "Delete the previous hook" gitlab_hook: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" hook_url: "https://my-ci-server.example.com/gitlab-hook" state: absent - name: "Delete a hook by numeric project id" gitlab_hook: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: 10 hook_url: "https://my-ci-server.example.com/gitlab-hook" state: absent ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" hook: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findProject class GitLabHook(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.hookObject = None ''' @param project Project Object @param hook_url Url to call on event @param description Description of the group @param parent Parent group full path ''' def createOrUpdateHook(self, project, hook_url, options): changed = False # Because we have already call userExists in main() if self.hookObject is None: hook = self.createHook(project, { 'url': hook_url, 'push_events': options['push_events'], 'issues_events': options['issues_events'], 'merge_requests_events': options['merge_requests_events'], 'tag_push_events': options['tag_push_events'], 'note_events': options['note_events'], 'job_events': options['job_events'], 'pipeline_events': options['pipeline_events'], 'wiki_page_events': options['wiki_page_events'], 'enable_ssl_verification': options['enable_ssl_verification'], 'token': options['token']}) changed = True else: changed, hook = self.updateHook(self.hookObject, { 'push_events': options['push_events'], 'issues_events': options['issues_events'], 'merge_requests_events': options['merge_requests_events'], 'tag_push_events': options['tag_push_events'], 'note_events': options['note_events'], 'job_events': options['job_events'], 'pipeline_events': options['pipeline_events'], 'wiki_page_events': options['wiki_page_events'], 'enable_ssl_verification': options['enable_ssl_verification'], 'token': options['token']}) self.hookObject = hook if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url) try: hook.save() except Exception as e: self._module.fail_json(msg="Failed to update hook: %s " % e) return True else: return False ''' @param project Project Object @param arguments Attributs of the hook ''' def createHook(self, project, arguments): if self._module.check_mode: return True hook = project.hooks.create(arguments) return hook ''' @param hook Hook Object @param arguments Attributs of the hook ''' def updateHook(self, hook, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(hook, arg_key) != arguments[arg_key]: setattr(hook, arg_key, arguments[arg_key]) changed = True return (changed, hook) ''' @param project Project object @param hook_url Url to call on event ''' def findHook(self, project, hook_url): hooks = project.hooks.list() for hook in hooks: if (hook.url == hook_url): return hook ''' @param project Project object @param hook_url Url to call on event ''' def existsHook(self, project, hook_url): # When project exists, object will be stored in self.projectObject. hook = self.findHook(project, hook_url) if hook: self.hookObject = hook return True return False def deleteHook(self): if self._module.check_mode: return True return self.hookObject.delete() def deprecation_warning(module): deprecated_aliases = ['private_token', 'access_token', 'enable_ssl_verification'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_token=dict(type='str', no_log=True, aliases=["private_token", "access_token"]), state=dict(type='str', default="present", choices=["absent", "present"]), project=dict(type='str', required=True), hook_url=dict(type='str', required=True), push_events=dict(type='bool', default=True), issues_events=dict(type='bool', default=False), merge_requests_events=dict(type='bool', default=False), tag_push_events=dict(type='bool', default=False), note_events=dict(type='bool', default=False), job_events=dict(type='bool', default=False), pipeline_events=dict(type='bool', default=False), wiki_page_events=dict(type='bool', default=False), hook_validate_certs=dict(type='bool', default=False, aliases=['enable_ssl_verification']), token=dict(type='str', no_log=True), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_username', 'api_token'], ['api_password', 'api_token'] ], required_together=[ ['api_username', 'api_password'] ], required_one_of=[ ['api_username', 'api_token'] ], supports_check_mode=True, ) deprecation_warning(module) gitlab_url = re.sub('/api.*', '', module.params['api_url']) validate_certs = module.params['validate_certs'] gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] state = module.params['state'] project_identifier = module.params['project'] hook_url = module.params['hook_url'] push_events = module.params['push_events'] issues_events = module.params['issues_events'] merge_requests_events = module.params['merge_requests_events'] tag_push_events = module.params['tag_push_events'] note_events = module.params['note_events'] job_events = module.params['job_events'] pipeline_events = module.params['pipeline_events'] wiki_page_events = module.params['wiki_page_events'] enable_ssl_verification = module.params['hook_validate_certs'] hook_token = module.params['token'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) gitlab_hook = GitLabHook(module, gitlab_instance) project = findProject(gitlab_instance, project_identifier) if project is None: module.fail_json(msg="Failed to create hook: project %s doesn't exists" % project_identifier) hook_exists = gitlab_hook.existsHook(project, hook_url) if state == 'absent': if hook_exists: gitlab_hook.deleteHook() module.exit_json(changed=True, msg="Successfully deleted hook %s" % hook_url) else: module.exit_json(changed=False, msg="Hook deleted or does not exists") if state == 'present': if gitlab_hook.createOrUpdateHook(project, hook_url, { "push_events": push_events, "issues_events": issues_events, "merge_requests_events": merge_requests_events, "tag_push_events": tag_push_events, "note_events": note_events, "job_events": job_events, "pipeline_events": pipeline_events, "wiki_page_events": wiki_page_events, "enable_ssl_verification": enable_ssl_verification, "token": hook_token}): module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url, hook=gitlab_hook.hookObject._attrs) else: module.exit_json(changed=False, msg="No need to update the hook %s" % hook_url, hook=gitlab_hook.hookObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,894
gitlab_group contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_group contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_group.py:273:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_group.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61894
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:16Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_project.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_project short_description: Creates/updates/deletes GitLab Projects description: - When the project does not exist in GitLab, it will be created. - When the project does exists and state=absent, the project will be deleted. - When changes are made to the project, the project will be updated. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token group: description: - Id or The full path of the group of which this projects belongs to. type: str name: description: - The name of the project required: true type: str path: description: - The path of the project you want to create, this will be server_url/<group>/path - If not supplied, name will be used. type: str description: description: - An description for the project. type: str issues_enabled: description: - Whether you want to create issues or not. - Possible values are true and false. type: bool default: yes merge_requests_enabled: description: - If merge requests can be made or not. - Possible values are true and false. type: bool default: yes wiki_enabled: description: - If an wiki for this project should be available or not. - Possible values are true and false. type: bool default: yes snippets_enabled: description: - If creating snippets should be available or not. - Possible values are true and false. type: bool default: yes visibility: description: - Private. Project access must be granted explicitly for each user. - Internal. The project can be cloned by any logged in user. - Public. The project can be cloned without any authentication. default: private type: str choices: ["private", "internal", "public"] aliases: - visibility_level import_url: description: - Git repository which will be imported into gitlab. - GitLab server needs read access to this git repository. required: false type: str state: description: - create or delete project. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] ''' EXAMPLES = ''' - name: Delete GitLab Project gitlab_project: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False name: my_first_project state: absent delegate_to: localhost - name: Create GitLab Project in group Ansible gitlab_project: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: my_first_project group: ansible issues_enabled: False wiki_enabled: True snippets_enabled: True import_url: http://git.example.com/example/lab.git state: present delegate_to: localhost ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" project: description: API object returned: always type: dict ''' import os import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup, findProject class GitLabProject(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.projectObject = None ''' @param project_name Name of the project @param namespace Namespace Object (User or Group) @param options Options of the project ''' def createOrUpdateProject(self, project_name, namespace, options): changed = False # Because we have already call userExists in main() if self.projectObject is None: project = self.createProject(namespace, { 'name': project_name, 'path': options['path'], 'description': options['description'], 'issues_enabled': options['issues_enabled'], 'merge_requests_enabled': options['merge_requests_enabled'], 'wiki_enabled': options['wiki_enabled'], 'snippets_enabled': options['snippets_enabled'], 'visibility': options['visibility'], 'import_url': options['import_url']}) changed = True else: changed, project = self.updateProject(self.projectObject, { 'name': project_name, 'description': options['description'], 'issues_enabled': options['issues_enabled'], 'merge_requests_enabled': options['merge_requests_enabled'], 'wiki_enabled': options['wiki_enabled'], 'snippets_enabled': options['snippets_enabled'], 'visibility': options['visibility']}) self.projectObject = project if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name) try: project.save() except Exception as e: self._module.fail_json(msg="Failed update project: %s " % e) return True else: return False ''' @param namespace Namespace Object (User or Group) @param arguments Attributs of the project ''' def createProject(self, namespace, arguments): if self._module.check_mode: return True arguments['namespace_id'] = namespace.id try: project = self._gitlab.projects.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create project: %s " % to_native(e)) return project ''' @param project Project Object @param arguments Attributs of the project ''' def updateProject(self, project, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(project, arg_key) != arguments[arg_key]: setattr(project, arg_key, arguments[arg_key]) changed = True return (changed, project) def deleteProject(self): if self._module.check_mode: return True project = self.projectObject return project.delete() ''' @param namespace User/Group object @param name Name of the project ''' def existsProject(self, namespace, path): # When project exists, object will be stored in self.projectObject. project = findProject(self._gitlab, namespace.full_path + '/' + path) if project: self.projectObject = project return True return False def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), group=dict(type='str'), name=dict(type='str', required=True), path=dict(type='str'), description=dict(type='str'), issues_enabled=dict(type='bool', default=True), merge_requests_enabled=dict(type='bool', default=True), wiki_enabled=dict(type='bool', default=True), snippets_enabled=dict(default=True, type='bool'), visibility=dict(type='str', default="private", choices=["internal", "private", "public"], aliases=["visibility_level"]), import_url=dict(type='str'), state=dict(type='str', default="present", choices=["absent", "present"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] group_identifier = module.params['group'] project_name = module.params['name'] project_path = module.params['path'] project_description = module.params['description'] issues_enabled = module.params['issues_enabled'] merge_requests_enabled = module.params['merge_requests_enabled'] wiki_enabled = module.params['wiki_enabled'] snippets_enabled = module.params['snippets_enabled'] visibility = module.params['visibility'] import_url = module.params['import_url'] state = module.params['state'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) # Set project_path to project_name if it is empty. if project_path is None: project_path = project_name.replace(" ", "_") gitlab_project = GitLabProject(module, gitlab_instance) if group_identifier: group = findGroup(gitlab_instance, group_identifier) if group is None: module.fail_json(msg="Failed to create project: group %s doesn't exists" % group_identifier) namespace = gitlab_instance.namespaces.get(group.id) project_exists = gitlab_project.existsProject(namespace, project_path) else: user = gitlab_instance.users.list(username=gitlab_instance.user.username)[0] namespace = gitlab_instance.namespaces.get(user.id) project_exists = gitlab_project.existsProject(namespace, project_path) if state == 'absent': if project_exists: gitlab_project.deleteProject() module.exit_json(changed=True, msg="Successfully deleted project %s" % project_name) else: module.exit_json(changed=False, msg="Project deleted or does not exists") if state == 'present': if gitlab_project.createOrUpdateProject(project_name, namespace, { "path": project_path, "description": project_description, "issues_enabled": issues_enabled, "merge_requests_enabled": merge_requests_enabled, "wiki_enabled": wiki_enabled, "snippets_enabled": snippets_enabled, "visibility": visibility, "import_url": import_url}): module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name, project=gitlab_project.projectObject._attrs) else: module.exit_json(changed=False, msg="No need to update the project %s" % project_name, project=gitlab_project.projectObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,894
gitlab_group contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_group contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_group.py:273:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_group.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61894
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:16Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_runner.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2018, Samy Coenen <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_runner short_description: Create, modify and delete GitLab Runners. description: - Register, update and delete runners with the GitLab API. - All operations are performed using the GitLab API v4. - For details, consult the full API documentation at U(https://docs.gitlab.com/ee/api/runners.html). - A valid private API token is required for all operations. You can create as many tokens as you like using the GitLab web interface at U(https://$GITLAB_URL/profile/personal_access_tokens). - A valid registration token is required for registering a new runner. To create shared runners, you need to ask your administrator to give you this token. It can be found at U(https://$GITLAB_URL/admin/runners/). notes: - To create a new runner at least the C(api_token), C(description) and C(url) options are required. - Runners need to have unique descriptions. version_added: 2.8 author: - Samy Coenen (@SamyCoenen) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab >= 1.5.0 extends_documentation_fragment: - auth_basic options: url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str api_token: description: - Your private token to interact with the GitLab API. required: True type: str aliases: - private_token description: description: - The unique name of the runner. required: True type: str aliases: - name state: description: - Make sure that the runner with the same name exists with the same configuration or delete the runner with the same name. required: False default: present choices: ["present", "absent"] type: str registration_token: description: - The registration token is used to register new runners. required: True type: str active: description: - Define if the runners is immediately active after creation. required: False default: yes type: bool locked: description: - Determines if the runner is locked or not. required: False default: False type: bool access_level: description: - Determines if a runner can pick up jobs from protected branches. required: False default: ref_protected choices: ["ref_protected", "not_protected"] type: str maximum_timeout: description: - The maximum timeout that a runner has to pick up a specific job. required: False default: 3600 type: int run_untagged: description: - Run untagged jobs or not. required: False default: yes type: bool tag_list: description: The tags that apply to the runner. required: False default: [] type: list ''' EXAMPLES = ''' - name: "Register runner" gitlab_runner: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" registration_token: 4gfdsg345 description: Docker Machine t1 state: present active: True tag_list: ['docker'] run_untagged: False locked: False - name: "Delete runner" gitlab_runner: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" description: Docker Machine t1 state: absent ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" runner: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native try: cmp except NameError: def cmp(a, b): return (a > b) - (a < b) class GitLabRunner(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.runnerObject = None def createOrUpdateRunner(self, description, options): changed = False # Because we have already call userExists in main() if self.runnerObject is None: runner = self.createRunner({ 'description': description, 'active': options['active'], 'token': options['registration_token'], 'locked': options['locked'], 'run_untagged': options['run_untagged'], 'maximum_timeout': options['maximum_timeout'], 'tag_list': options['tag_list']}) changed = True else: changed, runner = self.updateRunner(self.runnerObject, { 'active': options['active'], 'locked': options['locked'], 'run_untagged': options['run_untagged'], 'maximum_timeout': options['maximum_timeout'], 'access_level': options['access_level'], 'tag_list': options['tag_list']}) self.runnerObject = runner if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the runner %s" % description) try: runner.save() except Exception as e: self._module.fail_json(msg="Failed to update runner: %s " % to_native(e)) return True else: return False ''' @param arguments Attributs of the runner ''' def createRunner(self, arguments): if self._module.check_mode: return True try: runner = self._gitlab.runners.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create runner: %s " % to_native(e)) return runner ''' @param runner Runner object @param arguments Attributs of the runner ''' def updateRunner(self, runner, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if isinstance(arguments[arg_key], list): list1 = getattr(runner, arg_key) list1.sort() list2 = arguments[arg_key] list2.sort() if cmp(list1, list2): setattr(runner, arg_key, arguments[arg_key]) changed = True else: if getattr(runner, arg_key) != arguments[arg_key]: setattr(runner, arg_key, arguments[arg_key]) changed = True return (changed, runner) ''' @param description Description of the runner ''' def findRunner(self, description): runners = self._gitlab.runners.list(as_list=False) for runner in runners: if (runner.description == description): return self._gitlab.runners.get(runner.id) ''' @param description Description of the runner ''' def existsRunner(self, description): # When runner exists, object will be stored in self.runnerObject. runner = self.findRunner(description) if runner: self.runnerObject = runner return True return False def deleteRunner(self): if self._module.check_mode: return True runner = self.runnerObject return runner.delete() def deprecation_warning(module): deprecated_aliases = ['private_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( url=dict(type='str', removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["private_token"]), description=dict(type='str', required=True, aliases=["name"]), active=dict(type='bool', default=True), tag_list=dict(type='list', default=[]), run_untagged=dict(type='bool', default=True), locked=dict(type='bool', default=False), access_level=dict(type='str', default='ref_protected', choices=["not_protected", "ref_protected"]), maximum_timeout=dict(type='int', default=3600), registration_token=dict(type='str', required=True), state=dict(type='str', default="present", choices=["absent", "present"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'url'], ['api_username', 'api_token'], ['api_password', 'api_token'], ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token'], ['api_url', 'url'] ], supports_check_mode=True, ) deprecation_warning(module) if module.params['url'] is not None: url = re.sub('/api.*', '', module.params['url']) api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] gitlab_url = url if api_url is None else api_url gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] state = module.params['state'] runner_description = module.params['description'] runner_active = module.params['active'] tag_list = module.params['tag_list'] run_untagged = module.params['run_untagged'] runner_locked = module.params['locked'] access_level = module.params['access_level'] maximum_timeout = module.params['maximum_timeout'] registration_token = module.params['registration_token'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2" % to_native(e)) gitlab_runner = GitLabRunner(module, gitlab_instance) runner_exists = gitlab_runner.existsRunner(runner_description) if state == 'absent': if runner_exists: gitlab_runner.deleteRunner() module.exit_json(changed=True, msg="Successfully deleted runner %s" % runner_description) else: module.exit_json(changed=False, msg="Runner deleted or does not exists") if state == 'present': if gitlab_runner.createOrUpdateRunner(runner_description, { "active": runner_active, "tag_list": tag_list, "run_untagged": run_untagged, "locked": runner_locked, "access_level": access_level, "maximum_timeout": maximum_timeout, "registration_token": registration_token}): module.exit_json(changed=True, runner=gitlab_runner.runnerObject._attrs, msg="Successfully created or updated the runner %s" % runner_description) else: module.exit_json(changed=False, runner=gitlab_runner.runnerObject._attrs, msg="No need to update the runner %s" % runner_description) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,894
gitlab_group contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_group contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_group.py:273:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_group.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61894
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:16Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_user.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_user short_description: Creates/updates/deletes GitLab Users description: - When the user does not exist in GitLab, it will be created. - When the user does exists and state=absent, the user will be deleted. - When changes are made to user, the user will be updated. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module - administrator rights on the GitLab server extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token name: description: - Name of the user you want to create required: true type: str username: description: - The username of the user. required: true type: str password: description: - The password of the user. - GitLab server enforces minimum password length to 8, set this value with 8 or more characters. required: true type: str email: description: - The email that belongs to the user. required: true type: str sshkey_name: description: - The name of the sshkey type: str sshkey_file: description: - The ssh key itself. type: str group: description: - Id or Full path of parent group in the form of group/name - Add user as an member to this group. type: str access_level: description: - The access level to the group. One of the following can be used. - guest - reporter - developer - master (alias for maintainer) - maintainer - owner default: guest type: str choices: ["guest", "reporter", "developer", "master", "maintainer", "owner"] state: description: - create or delete group. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] confirm: description: - Require confirmation. type: bool default: yes version_added: "2.4" isadmin: description: - Grant admin privileges to the user type: bool default: no version_added: "2.8" external: description: - Define external parameter for this user type: bool default: no version_added: "2.8" ''' EXAMPLES = ''' - name: "Delete GitLab User" gitlab_user: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False username: myusername state: absent delegate_to: localhost - name: "Create GitLab User" gitlab_user: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: My Name username: myusername password: mysecretpassword email: [email protected] sshkey_name: MySSH sshkey_file: ssh-rsa AAAAB3NzaC1yc... state: present group: super_group/mon_group access_level: owner delegate_to: localhost ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" user: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup class GitLabUser(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.userObject = None self.ACCESS_LEVEL = { 'guest': gitlab.GUEST_ACCESS, 'reporter': gitlab.REPORTER_ACCESS, 'developer': gitlab.DEVELOPER_ACCESS, 'master': gitlab.MAINTAINER_ACCESS, 'maintainer': gitlab.MAINTAINER_ACCESS, 'owner': gitlab.OWNER_ACCESS} ''' @param username Username of the user @param options User options ''' def createOrUpdateUser(self, username, options): changed = False # Because we have already call userExists in main() if self.userObject is None: user = self.createUser({ 'name': options['name'], 'username': username, 'password': options['password'], 'email': options['email'], 'skip_confirmation': not options['confirm'], 'admin': options['isadmin'], 'external': options['external']}) changed = True else: changed, user = self.updateUser(self.userObject, { 'name': options['name'], 'email': options['email'], 'is_admin': options['isadmin'], 'external': options['external']}) # Assign ssh keys if options['sshkey_name'] and options['sshkey_file']: key_changed = self.addSshKeyToUser(user, { 'name': options['sshkey_name'], 'file': options['sshkey_file']}) changed = changed or key_changed # Assign group if options['group_path']: group_changed = self.assignUserToGroup(user, options['group_path'], options['access_level']) changed = changed or group_changed self.userObject = user if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the user %s" % username) try: user.save() except Exception as e: self._module.fail_json(msg="Failed to update user: %s " % to_native(e)) return True else: return False ''' @param group User object ''' def getUserId(self, user): if user is not None: return user.id return None ''' @param user User object @param sshkey_name Name of the ssh key ''' def sshKeyExists(self, user, sshkey_name): keyList = map(lambda k: k.title, user.keys.list()) return sshkey_name in keyList ''' @param user User object @param sshkey Dict containing sshkey infos {"name": "", "file": ""} ''' def addSshKeyToUser(self, user, sshkey): if not self.sshKeyExists(user, sshkey['name']): if self._module.check_mode: return True try: user.keys.create({ 'title': sshkey['name'], 'key': sshkey['file']}) except gitlab.exceptions.GitlabCreateError as e: self._module.fail_json(msg="Failed to assign sshkey to user: %s" % to_native(e)) return True return False ''' @param group Group object @param user_id Id of the user to find ''' def findMember(self, group, user_id): try: member = group.members.get(user_id) except gitlab.exceptions.GitlabGetError as e: return None return member ''' @param group Group object @param user_id Id of the user to check ''' def memberExists(self, group, user_id): member = self.findMember(group, user_id) return member is not None ''' @param group Group object @param user_id Id of the user to check @param access_level GitLab access_level to check ''' def memberAsGoodAccessLevel(self, group, user_id, access_level): member = self.findMember(group, user_id) return member.access_level == access_level ''' @param user User object @param group_path Complete path of the Group including parent group path. <parent_path>/<group_path> @param access_level GitLab access_level to assign ''' def assignUserToGroup(self, user, group_identifier, access_level): group = findGroup(self._gitlab, group_identifier) if self._module.check_mode: return True if group is None: return False if self.memberExists(group, self.getUserId(user)): member = self.findMember(group, self.getUserId(user)) if not self.memberAsGoodAccessLevel(group, member.id, self.ACCESS_LEVEL[access_level]): member.access_level = self.ACCESS_LEVEL[access_level] member.save() return True else: try: group.members.create({ 'user_id': self.getUserId(user), 'access_level': self.ACCESS_LEVEL[access_level]}) except gitlab.exceptions.GitlabCreateError as e: self._module.fail_json(msg="Failed to assign user to group: %s" % to_native(e)) return True return False ''' @param user User object @param arguments User attributes ''' def updateUser(self, user, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(user, arg_key) != arguments[arg_key]: setattr(user, arg_key, arguments[arg_key]) changed = True return (changed, user) ''' @param arguments User attributes ''' def createUser(self, arguments): if self._module.check_mode: return True try: user = self._gitlab.users.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create user: %s " % to_native(e)) return user ''' @param username Username of the user ''' def findUser(self, username): users = self._gitlab.users.list(search=username) for user in users: if (user.username == username): return user ''' @param username Username of the user ''' def existsUser(self, username): # When user exists, object will be stored in self.userObject. user = self.findUser(username) if user: self.userObject = user return True return False def deleteUser(self): if self._module.check_mode: return True user = self.userObject return user.delete() def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), name=dict(type='str', required=True), state=dict(type='str', default="present", choices=["absent", "present"]), username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), email=dict(type='str', required=True), sshkey_name=dict(type='str'), sshkey_file=dict(type='str'), group=dict(type='str'), access_level=dict(type='str', default="guest", choices=["developer", "guest", "maintainer", "master", "owner", "reporter"]), confirm=dict(type='bool', default=True), isadmin=dict(type='bool', default=False), external=dict(type='bool', default=False), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] user_name = module.params['name'] state = module.params['state'] user_username = module.params['username'].lower() user_password = module.params['password'] user_email = module.params['email'] user_sshkey_name = module.params['sshkey_name'] user_sshkey_file = module.params['sshkey_file'] group_path = module.params['group'] access_level = module.params['access_level'] confirm = module.params['confirm'] user_isadmin = module.params['isadmin'] user_external = module.params['external'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) gitlab_user = GitLabUser(module, gitlab_instance) user_exists = gitlab_user.existsUser(user_username) if state == 'absent': if user_exists: gitlab_user.deleteUser() module.exit_json(changed=True, msg="Successfully deleted user %s" % user_username) else: module.exit_json(changed=False, msg="User deleted or does not exists") if state == 'present': if gitlab_user.createOrUpdateUser(user_username, { "name": user_name, "password": user_password, "email": user_email, "sshkey_name": user_sshkey_name, "sshkey_file": user_sshkey_file, "group_path": group_path, "access_level": access_level, "confirm": confirm, "isadmin": user_isadmin, "external": user_external}): module.exit_json(changed=True, msg="Successfully created or updated the user %s" % user_username, user=gitlab_user.userObject._attrs) else: module.exit_json(changed=False, msg="No need to update the user %s" % user_username, user=gitlab_user.userObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,893
gitlab_deploy_key contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_deploy_key contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_deploy_key.py:244:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_deploy_key.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61893
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:15Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_deploy_key.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2018, Marcus Watkins <[email protected]> # Based on code: # Copyright: (c) 2013, Phillip Gentry <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: gitlab_deploy_key short_description: Manages GitLab project deploy keys. description: - Adds, updates and removes project deploy keys version_added: "2.6" author: - Marcus Watkins (@marwatk) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: api_token: description: - GitLab token for logging in. version_added: "2.8" type: str aliases: - private_token - access_token project: description: - Id or Full path of project in the form of group/name required: true type: str title: description: - Deploy key's title required: true type: str key: description: - Deploy key required: true type: str can_push: description: - Whether this key can push to the project type: bool default: no state: description: - When C(present) the deploy key added to the project if it doesn't exist. - When C(absent) it will be removed from the project if it exists required: true default: present type: str choices: [ "present", "absent" ] ''' EXAMPLES = ''' - name: "Adding a project deploy key" gitlab_deploy_key: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" title: "Jenkins CI" state: present key: "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt4596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9w..." - name: "Update the above deploy key to add push access" gitlab_deploy_key: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" title: "Jenkins CI" state: present can_push: yes - name: "Remove the previous deploy key from the project" gitlab_deploy_key: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" state: absent key: "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt4596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9w..." ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: key is already in use" deploy_key: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findProject class GitLabDeployKey(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.deployKeyObject = None ''' @param project Project object @param key_title Title of the key @param key_key String of the key @param key_can_push Option of the deployKey @param options Deploy key options ''' def createOrUpdateDeployKey(self, project, key_title, key_key, options): changed = False # Because we have already call existsDeployKey in main() if self.deployKeyObject is None: deployKey = self.createDeployKey(project, { 'title': key_title, 'key': key_key, 'can_push': options['can_push']}) changed = True else: changed, deployKey = self.updateDeployKey(self.deployKeyObject, { 'can_push': options['can_push']}) self.deployKeyObject = deployKey if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title) try: deployKey.save() except Exception as e: self._module.fail_json(msg="Failed to update deploy key: %s " % e) return True else: return False ''' @param project Project Object @param arguments Attributs of the deployKey ''' def createDeployKey(self, project, arguments): if self._module.check_mode: return True try: deployKey = project.keys.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create deploy key: %s " % to_native(e)) return deployKey ''' @param deployKey Deploy Key Object @param arguments Attributs of the deployKey ''' def updateDeployKey(self, deployKey, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(deployKey, arg_key) != arguments[arg_key]: setattr(deployKey, arg_key, arguments[arg_key]) changed = True return (changed, deployKey) ''' @param project Project object @param key_title Title of the key ''' def findDeployKey(self, project, key_title): deployKeys = project.keys.list() for deployKey in deployKeys: if (deployKey.title == key_title): return deployKey ''' @param project Project object @param key_title Title of the key ''' def existsDeployKey(self, project, key_title): # When project exists, object will be stored in self.projectObject. deployKey = self.findDeployKey(project, key_title) if deployKey: self.deployKeyObject = deployKey return True return False def deleteDeployKey(self): if self._module.check_mode: return True return self.deployKeyObject.delete() def deprecation_warning(module): deprecated_aliases = ['private_token', 'access_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_token=dict(type='str', no_log=True, aliases=["private_token", "access_token"]), state=dict(type='str', default="present", choices=["absent", "present"]), project=dict(type='str', required=True), key=dict(type='str', required=True), can_push=dict(type='bool', default=False), title=dict(type='str', required=True) )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_username', 'api_token'], ['api_password', 'api_token'] ], required_together=[ ['api_username', 'api_password'] ], required_one_of=[ ['api_username', 'api_token'] ], supports_check_mode=True, ) deprecation_warning(module) gitlab_url = re.sub('/api.*', '', module.params['api_url']) validate_certs = module.params['validate_certs'] gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] state = module.params['state'] project_identifier = module.params['project'] key_title = module.params['title'] key_keyfile = module.params['key'] key_can_push = module.params['can_push'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) gitlab_deploy_key = GitLabDeployKey(module, gitlab_instance) project = findProject(gitlab_instance, project_identifier) if project is None: module.fail_json(msg="Failed to create deploy key: project %s doesn't exists" % project_identifier) deployKey_exists = gitlab_deploy_key.existsDeployKey(project, key_title) if state == 'absent': if deployKey_exists: gitlab_deploy_key.deleteDeployKey() module.exit_json(changed=True, msg="Successfully deleted deploy key %s" % key_title) else: module.exit_json(changed=False, msg="Deploy key deleted or does not exists") if state == 'present': if gitlab_deploy_key.createOrUpdateDeployKey(project, key_title, key_keyfile, {'can_push': key_can_push}): module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title, deploy_key=gitlab_deploy_key.deployKeyObject._attrs) else: module.exit_json(changed=False, msg="No need to update the deploy key %s" % key_title, deploy_key=gitlab_deploy_key.deployKeyObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,893
gitlab_deploy_key contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_deploy_key contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_deploy_key.py:244:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_deploy_key.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61893
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:15Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_group.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_group short_description: Creates/updates/deletes GitLab Groups description: - When the group does not exist in GitLab, it will be created. - When the group does exist and state=absent, the group will be deleted. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token name: description: - Name of the group you want to create. required: true type: str path: description: - The path of the group you want to create, this will be server_url/group_path - If not supplied, the group_name will be used. type: str description: description: - A description for the group. version_added: "2.7" type: str state: description: - create or delete group. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] parent: description: - Allow to create subgroups - Id or Full path of parent group in the form of group/name version_added: "2.8" type: str visibility: description: - Default visibility of the group version_added: "2.8" choices: ["private", "internal", "public"] default: private type: str ''' EXAMPLES = ''' - name: "Delete GitLab Group" gitlab_group: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False name: my_first_group state: absent - name: "Create GitLab Group" gitlab_group: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: my_first_group path: my_first_group state: present # The group will by created at https://gitlab.dj-wasabi.local/super_parent/parent/my_first_group - name: "Create GitLab SubGroup" gitlab_group: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: my_first_group path: my_first_group state: present parent: "super_parent/parent" ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" group: description: API object returned: always type: dict ''' import os import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup class GitLabGroup(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.groupObject = None ''' @param group Group object ''' def getGroupId(self, group): if group is not None: return group.id return None ''' @param name Name of the group @param parent Parent group full path @param options Group options ''' def createOrUpdateGroup(self, name, parent, options): changed = False # Because we have already call userExists in main() if self.groupObject is None: parent_id = self.getGroupId(parent) group = self.createGroup({ 'name': name, 'path': options['path'], 'parent_id': parent_id, 'visibility': options['visibility']}) changed = True else: changed, group = self.updateGroup(self.groupObject, { 'name': name, 'description': options['description'], 'visibility': options['visibility']}) self.groupObject = group if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the group %s" % name) try: group.save() except Exception as e: self._module.fail_json(msg="Failed to update group: %s " % e) return True else: return False ''' @param arguments Attributs of the group ''' def createGroup(self, arguments): if self._module.check_mode: return True try: group = self._gitlab.groups.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create group: %s " % to_native(e)) return group ''' @param group Group Object @param arguments Attributs of the group ''' def updateGroup(self, group, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(group, arg_key) != arguments[arg_key]: setattr(group, arg_key, arguments[arg_key]) changed = True return (changed, group) def deleteGroup(self): group = self.groupObject if len(group.projects.list()) >= 1: self._module.fail_json( msg="There are still projects in this group. These needs to be moved or deleted before this group can be removed.") else: if self._module.check_mode: return True try: group.delete() except Exception as e: self._module.fail_json(msg="Failed to delete group: %s " % to_native(e)) ''' @param name Name of the groupe @param full_path Complete path of the Group including parent group path. <parent_path>/<group_path> ''' def existsGroup(self, project_identifier): # When group/user exists, object will be stored in self.groupObject. group = findGroup(self._gitlab, project_identifier) if group: self.groupObject = group return True return False def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), name=dict(type='str', required=True), path=dict(type='str'), description=dict(type='str'), state=dict(type='str', default="present", choices=["absent", "present"]), parent=dict(type='str'), visibility=dict(type='str', default="private", choices=["internal", "private", "public"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] group_name = module.params['name'] group_path = module.params['path'] description = module.params['description'] state = module.params['state'] parent_identifier = module.params['parent'] group_visibility = module.params['visibility'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2" % to_native(e)) # Define default group_path based on group_name if group_path is None: group_path = group_name.replace(" ", "_") gitlab_group = GitLabGroup(module, gitlab_instance) parent_group = None if parent_identifier: parent_group = findGroup(gitlab_instance, parent_identifier) if not parent_group: module.fail_json(msg="Failed create GitLab group: Parent group doesn't exists") group_exists = gitlab_group.existsGroup(parent_group.full_path + '/' + group_path) else: group_exists = gitlab_group.existsGroup(group_path) if state == 'absent': if group_exists: gitlab_group.deleteGroup() module.exit_json(changed=True, msg="Successfully deleted group %s" % group_name) else: module.exit_json(changed=False, msg="Group deleted or does not exists") if state == 'present': if gitlab_group.createOrUpdateGroup(group_name, parent_group, { "path": group_path, "description": description, "visibility": group_visibility}): module.exit_json(changed=True, msg="Successfully created or updated the group %s" % group_name, group=gitlab_group.groupObject._attrs) else: module.exit_json(changed=False, msg="No need to update the group %s" % group_name, group=gitlab_group.groupObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,893
gitlab_deploy_key contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_deploy_key contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_deploy_key.py:244:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_deploy_key.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61893
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:15Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_hook.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2018, Marcus Watkins <[email protected]> # Based on code: # Copyright: (c) 2013, Phillip Gentry <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_hook short_description: Manages GitLab project hooks. description: - Adds, updates and removes project hook version_added: "2.6" author: - Marcus Watkins (@marwatk) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: api_token: description: - GitLab token for logging in. version_added: "2.8" type: str aliases: - private_token - access_token project: description: - Id or Full path of the project in the form of group/name. required: true type: str hook_url: description: - The url that you want GitLab to post to, this is used as the primary key for updates and deletion. required: true type: str state: description: - When C(present) the hook will be updated to match the input or created if it doesn't exist. - When C(absent) hook will be deleted if it exists. required: true default: present type: str choices: [ "present", "absent" ] push_events: description: - Trigger hook on push events. type: bool default: yes issues_events: description: - Trigger hook on issues events. type: bool default: no merge_requests_events: description: - Trigger hook on merge requests events. type: bool default: no tag_push_events: description: - Trigger hook on tag push events. type: bool default: no note_events: description: - Trigger hook on note events or when someone adds a comment. type: bool default: no job_events: description: - Trigger hook on job events. type: bool default: no pipeline_events: description: - Trigger hook on pipeline events. type: bool default: no wiki_page_events: description: - Trigger hook on wiki events. type: bool default: no hook_validate_certs: description: - Whether GitLab will do SSL verification when triggering the hook. type: bool default: no aliases: [ enable_ssl_verification ] token: description: - Secret token to validate hook messages at the receiver. - If this is present it will always result in a change as it cannot be retrieved from GitLab. - Will show up in the X-GitLab-Token HTTP request header. required: false type: str ''' EXAMPLES = ''' - name: "Adding a project hook" gitlab_hook: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" hook_url: "https://my-ci-server.example.com/gitlab-hook" state: present push_events: yes tag_push_events: yes hook_validate_certs: no token: "my-super-secret-token-that-my-ci-server-will-check" - name: "Delete the previous hook" gitlab_hook: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: "my_group/my_project" hook_url: "https://my-ci-server.example.com/gitlab-hook" state: absent - name: "Delete a hook by numeric project id" gitlab_hook: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" project: 10 hook_url: "https://my-ci-server.example.com/gitlab-hook" state: absent ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" hook: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findProject class GitLabHook(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.hookObject = None ''' @param project Project Object @param hook_url Url to call on event @param description Description of the group @param parent Parent group full path ''' def createOrUpdateHook(self, project, hook_url, options): changed = False # Because we have already call userExists in main() if self.hookObject is None: hook = self.createHook(project, { 'url': hook_url, 'push_events': options['push_events'], 'issues_events': options['issues_events'], 'merge_requests_events': options['merge_requests_events'], 'tag_push_events': options['tag_push_events'], 'note_events': options['note_events'], 'job_events': options['job_events'], 'pipeline_events': options['pipeline_events'], 'wiki_page_events': options['wiki_page_events'], 'enable_ssl_verification': options['enable_ssl_verification'], 'token': options['token']}) changed = True else: changed, hook = self.updateHook(self.hookObject, { 'push_events': options['push_events'], 'issues_events': options['issues_events'], 'merge_requests_events': options['merge_requests_events'], 'tag_push_events': options['tag_push_events'], 'note_events': options['note_events'], 'job_events': options['job_events'], 'pipeline_events': options['pipeline_events'], 'wiki_page_events': options['wiki_page_events'], 'enable_ssl_verification': options['enable_ssl_verification'], 'token': options['token']}) self.hookObject = hook if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url) try: hook.save() except Exception as e: self._module.fail_json(msg="Failed to update hook: %s " % e) return True else: return False ''' @param project Project Object @param arguments Attributs of the hook ''' def createHook(self, project, arguments): if self._module.check_mode: return True hook = project.hooks.create(arguments) return hook ''' @param hook Hook Object @param arguments Attributs of the hook ''' def updateHook(self, hook, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(hook, arg_key) != arguments[arg_key]: setattr(hook, arg_key, arguments[arg_key]) changed = True return (changed, hook) ''' @param project Project object @param hook_url Url to call on event ''' def findHook(self, project, hook_url): hooks = project.hooks.list() for hook in hooks: if (hook.url == hook_url): return hook ''' @param project Project object @param hook_url Url to call on event ''' def existsHook(self, project, hook_url): # When project exists, object will be stored in self.projectObject. hook = self.findHook(project, hook_url) if hook: self.hookObject = hook return True return False def deleteHook(self): if self._module.check_mode: return True return self.hookObject.delete() def deprecation_warning(module): deprecated_aliases = ['private_token', 'access_token', 'enable_ssl_verification'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_token=dict(type='str', no_log=True, aliases=["private_token", "access_token"]), state=dict(type='str', default="present", choices=["absent", "present"]), project=dict(type='str', required=True), hook_url=dict(type='str', required=True), push_events=dict(type='bool', default=True), issues_events=dict(type='bool', default=False), merge_requests_events=dict(type='bool', default=False), tag_push_events=dict(type='bool', default=False), note_events=dict(type='bool', default=False), job_events=dict(type='bool', default=False), pipeline_events=dict(type='bool', default=False), wiki_page_events=dict(type='bool', default=False), hook_validate_certs=dict(type='bool', default=False, aliases=['enable_ssl_verification']), token=dict(type='str', no_log=True), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_username', 'api_token'], ['api_password', 'api_token'] ], required_together=[ ['api_username', 'api_password'] ], required_one_of=[ ['api_username', 'api_token'] ], supports_check_mode=True, ) deprecation_warning(module) gitlab_url = re.sub('/api.*', '', module.params['api_url']) validate_certs = module.params['validate_certs'] gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] state = module.params['state'] project_identifier = module.params['project'] hook_url = module.params['hook_url'] push_events = module.params['push_events'] issues_events = module.params['issues_events'] merge_requests_events = module.params['merge_requests_events'] tag_push_events = module.params['tag_push_events'] note_events = module.params['note_events'] job_events = module.params['job_events'] pipeline_events = module.params['pipeline_events'] wiki_page_events = module.params['wiki_page_events'] enable_ssl_verification = module.params['hook_validate_certs'] hook_token = module.params['token'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) gitlab_hook = GitLabHook(module, gitlab_instance) project = findProject(gitlab_instance, project_identifier) if project is None: module.fail_json(msg="Failed to create hook: project %s doesn't exists" % project_identifier) hook_exists = gitlab_hook.existsHook(project, hook_url) if state == 'absent': if hook_exists: gitlab_hook.deleteHook() module.exit_json(changed=True, msg="Successfully deleted hook %s" % hook_url) else: module.exit_json(changed=False, msg="Hook deleted or does not exists") if state == 'present': if gitlab_hook.createOrUpdateHook(project, hook_url, { "push_events": push_events, "issues_events": issues_events, "merge_requests_events": merge_requests_events, "tag_push_events": tag_push_events, "note_events": note_events, "job_events": job_events, "pipeline_events": pipeline_events, "wiki_page_events": wiki_page_events, "enable_ssl_verification": enable_ssl_verification, "token": hook_token}): module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url, hook=gitlab_hook.hookObject._attrs) else: module.exit_json(changed=False, msg="No need to update the hook %s" % hook_url, hook=gitlab_hook.hookObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,893
gitlab_deploy_key contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_deploy_key contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_deploy_key.py:244:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_deploy_key.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61893
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:15Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_project.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_project short_description: Creates/updates/deletes GitLab Projects description: - When the project does not exist in GitLab, it will be created. - When the project does exists and state=absent, the project will be deleted. - When changes are made to the project, the project will be updated. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token group: description: - Id or The full path of the group of which this projects belongs to. type: str name: description: - The name of the project required: true type: str path: description: - The path of the project you want to create, this will be server_url/<group>/path - If not supplied, name will be used. type: str description: description: - An description for the project. type: str issues_enabled: description: - Whether you want to create issues or not. - Possible values are true and false. type: bool default: yes merge_requests_enabled: description: - If merge requests can be made or not. - Possible values are true and false. type: bool default: yes wiki_enabled: description: - If an wiki for this project should be available or not. - Possible values are true and false. type: bool default: yes snippets_enabled: description: - If creating snippets should be available or not. - Possible values are true and false. type: bool default: yes visibility: description: - Private. Project access must be granted explicitly for each user. - Internal. The project can be cloned by any logged in user. - Public. The project can be cloned without any authentication. default: private type: str choices: ["private", "internal", "public"] aliases: - visibility_level import_url: description: - Git repository which will be imported into gitlab. - GitLab server needs read access to this git repository. required: false type: str state: description: - create or delete project. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] ''' EXAMPLES = ''' - name: Delete GitLab Project gitlab_project: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False name: my_first_project state: absent delegate_to: localhost - name: Create GitLab Project in group Ansible gitlab_project: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: my_first_project group: ansible issues_enabled: False wiki_enabled: True snippets_enabled: True import_url: http://git.example.com/example/lab.git state: present delegate_to: localhost ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" project: description: API object returned: always type: dict ''' import os import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup, findProject class GitLabProject(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.projectObject = None ''' @param project_name Name of the project @param namespace Namespace Object (User or Group) @param options Options of the project ''' def createOrUpdateProject(self, project_name, namespace, options): changed = False # Because we have already call userExists in main() if self.projectObject is None: project = self.createProject(namespace, { 'name': project_name, 'path': options['path'], 'description': options['description'], 'issues_enabled': options['issues_enabled'], 'merge_requests_enabled': options['merge_requests_enabled'], 'wiki_enabled': options['wiki_enabled'], 'snippets_enabled': options['snippets_enabled'], 'visibility': options['visibility'], 'import_url': options['import_url']}) changed = True else: changed, project = self.updateProject(self.projectObject, { 'name': project_name, 'description': options['description'], 'issues_enabled': options['issues_enabled'], 'merge_requests_enabled': options['merge_requests_enabled'], 'wiki_enabled': options['wiki_enabled'], 'snippets_enabled': options['snippets_enabled'], 'visibility': options['visibility']}) self.projectObject = project if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name) try: project.save() except Exception as e: self._module.fail_json(msg="Failed update project: %s " % e) return True else: return False ''' @param namespace Namespace Object (User or Group) @param arguments Attributs of the project ''' def createProject(self, namespace, arguments): if self._module.check_mode: return True arguments['namespace_id'] = namespace.id try: project = self._gitlab.projects.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create project: %s " % to_native(e)) return project ''' @param project Project Object @param arguments Attributs of the project ''' def updateProject(self, project, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(project, arg_key) != arguments[arg_key]: setattr(project, arg_key, arguments[arg_key]) changed = True return (changed, project) def deleteProject(self): if self._module.check_mode: return True project = self.projectObject return project.delete() ''' @param namespace User/Group object @param name Name of the project ''' def existsProject(self, namespace, path): # When project exists, object will be stored in self.projectObject. project = findProject(self._gitlab, namespace.full_path + '/' + path) if project: self.projectObject = project return True return False def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), group=dict(type='str'), name=dict(type='str', required=True), path=dict(type='str'), description=dict(type='str'), issues_enabled=dict(type='bool', default=True), merge_requests_enabled=dict(type='bool', default=True), wiki_enabled=dict(type='bool', default=True), snippets_enabled=dict(default=True, type='bool'), visibility=dict(type='str', default="private", choices=["internal", "private", "public"], aliases=["visibility_level"]), import_url=dict(type='str'), state=dict(type='str', default="present", choices=["absent", "present"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] group_identifier = module.params['group'] project_name = module.params['name'] project_path = module.params['path'] project_description = module.params['description'] issues_enabled = module.params['issues_enabled'] merge_requests_enabled = module.params['merge_requests_enabled'] wiki_enabled = module.params['wiki_enabled'] snippets_enabled = module.params['snippets_enabled'] visibility = module.params['visibility'] import_url = module.params['import_url'] state = module.params['state'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) # Set project_path to project_name if it is empty. if project_path is None: project_path = project_name.replace(" ", "_") gitlab_project = GitLabProject(module, gitlab_instance) if group_identifier: group = findGroup(gitlab_instance, group_identifier) if group is None: module.fail_json(msg="Failed to create project: group %s doesn't exists" % group_identifier) namespace = gitlab_instance.namespaces.get(group.id) project_exists = gitlab_project.existsProject(namespace, project_path) else: user = gitlab_instance.users.list(username=gitlab_instance.user.username)[0] namespace = gitlab_instance.namespaces.get(user.id) project_exists = gitlab_project.existsProject(namespace, project_path) if state == 'absent': if project_exists: gitlab_project.deleteProject() module.exit_json(changed=True, msg="Successfully deleted project %s" % project_name) else: module.exit_json(changed=False, msg="Project deleted or does not exists") if state == 'present': if gitlab_project.createOrUpdateProject(project_name, namespace, { "path": project_path, "description": project_description, "issues_enabled": issues_enabled, "merge_requests_enabled": merge_requests_enabled, "wiki_enabled": wiki_enabled, "snippets_enabled": snippets_enabled, "visibility": visibility, "import_url": import_url}): module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name, project=gitlab_project.projectObject._attrs) else: module.exit_json(changed=False, msg="No need to update the project %s" % project_name, project=gitlab_project.projectObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,893
gitlab_deploy_key contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_deploy_key contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_deploy_key.py:244:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_deploy_key.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61893
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:15Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_runner.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2018, Samy Coenen <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_runner short_description: Create, modify and delete GitLab Runners. description: - Register, update and delete runners with the GitLab API. - All operations are performed using the GitLab API v4. - For details, consult the full API documentation at U(https://docs.gitlab.com/ee/api/runners.html). - A valid private API token is required for all operations. You can create as many tokens as you like using the GitLab web interface at U(https://$GITLAB_URL/profile/personal_access_tokens). - A valid registration token is required for registering a new runner. To create shared runners, you need to ask your administrator to give you this token. It can be found at U(https://$GITLAB_URL/admin/runners/). notes: - To create a new runner at least the C(api_token), C(description) and C(url) options are required. - Runners need to have unique descriptions. version_added: 2.8 author: - Samy Coenen (@SamyCoenen) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab >= 1.5.0 extends_documentation_fragment: - auth_basic options: url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str api_token: description: - Your private token to interact with the GitLab API. required: True type: str aliases: - private_token description: description: - The unique name of the runner. required: True type: str aliases: - name state: description: - Make sure that the runner with the same name exists with the same configuration or delete the runner with the same name. required: False default: present choices: ["present", "absent"] type: str registration_token: description: - The registration token is used to register new runners. required: True type: str active: description: - Define if the runners is immediately active after creation. required: False default: yes type: bool locked: description: - Determines if the runner is locked or not. required: False default: False type: bool access_level: description: - Determines if a runner can pick up jobs from protected branches. required: False default: ref_protected choices: ["ref_protected", "not_protected"] type: str maximum_timeout: description: - The maximum timeout that a runner has to pick up a specific job. required: False default: 3600 type: int run_untagged: description: - Run untagged jobs or not. required: False default: yes type: bool tag_list: description: The tags that apply to the runner. required: False default: [] type: list ''' EXAMPLES = ''' - name: "Register runner" gitlab_runner: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" registration_token: 4gfdsg345 description: Docker Machine t1 state: present active: True tag_list: ['docker'] run_untagged: False locked: False - name: "Delete runner" gitlab_runner: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" description: Docker Machine t1 state: absent ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" runner: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native try: cmp except NameError: def cmp(a, b): return (a > b) - (a < b) class GitLabRunner(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.runnerObject = None def createOrUpdateRunner(self, description, options): changed = False # Because we have already call userExists in main() if self.runnerObject is None: runner = self.createRunner({ 'description': description, 'active': options['active'], 'token': options['registration_token'], 'locked': options['locked'], 'run_untagged': options['run_untagged'], 'maximum_timeout': options['maximum_timeout'], 'tag_list': options['tag_list']}) changed = True else: changed, runner = self.updateRunner(self.runnerObject, { 'active': options['active'], 'locked': options['locked'], 'run_untagged': options['run_untagged'], 'maximum_timeout': options['maximum_timeout'], 'access_level': options['access_level'], 'tag_list': options['tag_list']}) self.runnerObject = runner if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the runner %s" % description) try: runner.save() except Exception as e: self._module.fail_json(msg="Failed to update runner: %s " % to_native(e)) return True else: return False ''' @param arguments Attributs of the runner ''' def createRunner(self, arguments): if self._module.check_mode: return True try: runner = self._gitlab.runners.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create runner: %s " % to_native(e)) return runner ''' @param runner Runner object @param arguments Attributs of the runner ''' def updateRunner(self, runner, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if isinstance(arguments[arg_key], list): list1 = getattr(runner, arg_key) list1.sort() list2 = arguments[arg_key] list2.sort() if cmp(list1, list2): setattr(runner, arg_key, arguments[arg_key]) changed = True else: if getattr(runner, arg_key) != arguments[arg_key]: setattr(runner, arg_key, arguments[arg_key]) changed = True return (changed, runner) ''' @param description Description of the runner ''' def findRunner(self, description): runners = self._gitlab.runners.list(as_list=False) for runner in runners: if (runner.description == description): return self._gitlab.runners.get(runner.id) ''' @param description Description of the runner ''' def existsRunner(self, description): # When runner exists, object will be stored in self.runnerObject. runner = self.findRunner(description) if runner: self.runnerObject = runner return True return False def deleteRunner(self): if self._module.check_mode: return True runner = self.runnerObject return runner.delete() def deprecation_warning(module): deprecated_aliases = ['private_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( url=dict(type='str', removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["private_token"]), description=dict(type='str', required=True, aliases=["name"]), active=dict(type='bool', default=True), tag_list=dict(type='list', default=[]), run_untagged=dict(type='bool', default=True), locked=dict(type='bool', default=False), access_level=dict(type='str', default='ref_protected', choices=["not_protected", "ref_protected"]), maximum_timeout=dict(type='int', default=3600), registration_token=dict(type='str', required=True), state=dict(type='str', default="present", choices=["absent", "present"]), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'url'], ['api_username', 'api_token'], ['api_password', 'api_token'], ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token'], ['api_url', 'url'] ], supports_check_mode=True, ) deprecation_warning(module) if module.params['url'] is not None: url = re.sub('/api.*', '', module.params['url']) api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] gitlab_url = url if api_url is None else api_url gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] state = module.params['state'] runner_description = module.params['description'] runner_active = module.params['active'] tag_list = module.params['tag_list'] run_untagged = module.params['run_untagged'] runner_locked = module.params['locked'] access_level = module.params['access_level'] maximum_timeout = module.params['maximum_timeout'] registration_token = module.params['registration_token'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2" % to_native(e)) gitlab_runner = GitLabRunner(module, gitlab_instance) runner_exists = gitlab_runner.existsRunner(runner_description) if state == 'absent': if runner_exists: gitlab_runner.deleteRunner() module.exit_json(changed=True, msg="Successfully deleted runner %s" % runner_description) else: module.exit_json(changed=False, msg="Runner deleted or does not exists") if state == 'present': if gitlab_runner.createOrUpdateRunner(runner_description, { "active": runner_active, "tag_list": tag_list, "run_untagged": run_untagged, "locked": runner_locked, "access_level": access_level, "maximum_timeout": maximum_timeout, "registration_token": registration_token}): module.exit_json(changed=True, runner=gitlab_runner.runnerObject._attrs, msg="Successfully created or updated the runner %s" % runner_description) else: module.exit_json(changed=False, runner=gitlab_runner.runnerObject._attrs, msg="No need to update the runner %s" % runner_description) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,893
gitlab_deploy_key contains deprecated call to be removed in 2.10
##### SUMMARY gitlab_deploy_key contains call to Display.deprecated or AnsibleModule.deprecate and is scheduled for removal ``` lib/ansible/modules/source_control/gitlab_deploy_key.py:244:4: ansible-deprecated-version: Deprecated version ('2.10') found in call to Display.deprecated or AnsibleModule.deprecate ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ``` lib/ansible/modules/source_control/gitlab_deploy_key.py ``` ##### ANSIBLE VERSION ``` 2.10 ``` ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE N/A ##### EXPECTED RESULTS N/A ##### ACTUAL RESULTS N/A
https://github.com/ansible/ansible/issues/61893
https://github.com/ansible/ansible/pull/61912
331d51fb16b05f09d3d24d6d6f8d705fa0db4ba7
f92c99b4135327629cc2c92995f00102fcf2f681
2019-09-05T20:41:15Z
python
2019-10-20T11:38:08Z
lib/ansible/modules/source_control/gitlab_user.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Guillaume Martinez ([email protected]) # Copyright: (c) 2015, Werner Dijkerman ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gitlab_user short_description: Creates/updates/deletes GitLab Users description: - When the user does not exist in GitLab, it will be created. - When the user does exists and state=absent, the user will be deleted. - When changes are made to user, the user will be updated. version_added: "2.1" author: - Werner Dijkerman (@dj-wasabi) - Guillaume Martinez (@Lunik) requirements: - python >= 2.7 - python-gitlab python module - administrator rights on the GitLab server extends_documentation_fragment: - auth_basic options: server_url: description: - The URL of the GitLab server, with protocol (i.e. http or https). type: str login_user: description: - GitLab user name. type: str login_password: description: - GitLab password for login_user type: str api_token: description: - GitLab token for logging in. type: str aliases: - login_token name: description: - Name of the user you want to create required: true type: str username: description: - The username of the user. required: true type: str password: description: - The password of the user. - GitLab server enforces minimum password length to 8, set this value with 8 or more characters. required: true type: str email: description: - The email that belongs to the user. required: true type: str sshkey_name: description: - The name of the sshkey type: str sshkey_file: description: - The ssh key itself. type: str group: description: - Id or Full path of parent group in the form of group/name - Add user as an member to this group. type: str access_level: description: - The access level to the group. One of the following can be used. - guest - reporter - developer - master (alias for maintainer) - maintainer - owner default: guest type: str choices: ["guest", "reporter", "developer", "master", "maintainer", "owner"] state: description: - create or delete group. - Possible values are present and absent. default: present type: str choices: ["present", "absent"] confirm: description: - Require confirmation. type: bool default: yes version_added: "2.4" isadmin: description: - Grant admin privileges to the user type: bool default: no version_added: "2.8" external: description: - Define external parameter for this user type: bool default: no version_added: "2.8" ''' EXAMPLES = ''' - name: "Delete GitLab User" gitlab_user: api_url: https://gitlab.example.com/ api_token: "{{ access_token }}" validate_certs: False username: myusername state: absent delegate_to: localhost - name: "Create GitLab User" gitlab_user: api_url: https://gitlab.example.com/ validate_certs: True api_username: dj-wasabi api_password: "MySecretPassword" name: My Name username: myusername password: mysecretpassword email: [email protected] sshkey_name: MySSH sshkey_file: ssh-rsa AAAAB3NzaC1yc... state: present group: super_group/mon_group access_level: owner delegate_to: localhost ''' RETURN = ''' msg: description: Success or failure message returned: always type: str sample: "Success" result: description: json parsed response from the server returned: always type: dict error: description: the error message returned by the GitLab API returned: failed type: str sample: "400: path is already in use" user: description: API object returned: always type: dict ''' import os import re import traceback GITLAB_IMP_ERR = None try: import gitlab HAS_GITLAB_PACKAGE = True except Exception: GITLAB_IMP_ERR = traceback.format_exc() HAS_GITLAB_PACKAGE = False from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native from ansible.module_utils.gitlab import findGroup class GitLabUser(object): def __init__(self, module, gitlab_instance): self._module = module self._gitlab = gitlab_instance self.userObject = None self.ACCESS_LEVEL = { 'guest': gitlab.GUEST_ACCESS, 'reporter': gitlab.REPORTER_ACCESS, 'developer': gitlab.DEVELOPER_ACCESS, 'master': gitlab.MAINTAINER_ACCESS, 'maintainer': gitlab.MAINTAINER_ACCESS, 'owner': gitlab.OWNER_ACCESS} ''' @param username Username of the user @param options User options ''' def createOrUpdateUser(self, username, options): changed = False # Because we have already call userExists in main() if self.userObject is None: user = self.createUser({ 'name': options['name'], 'username': username, 'password': options['password'], 'email': options['email'], 'skip_confirmation': not options['confirm'], 'admin': options['isadmin'], 'external': options['external']}) changed = True else: changed, user = self.updateUser(self.userObject, { 'name': options['name'], 'email': options['email'], 'is_admin': options['isadmin'], 'external': options['external']}) # Assign ssh keys if options['sshkey_name'] and options['sshkey_file']: key_changed = self.addSshKeyToUser(user, { 'name': options['sshkey_name'], 'file': options['sshkey_file']}) changed = changed or key_changed # Assign group if options['group_path']: group_changed = self.assignUserToGroup(user, options['group_path'], options['access_level']) changed = changed or group_changed self.userObject = user if changed: if self._module.check_mode: self._module.exit_json(changed=True, msg="Successfully created or updated the user %s" % username) try: user.save() except Exception as e: self._module.fail_json(msg="Failed to update user: %s " % to_native(e)) return True else: return False ''' @param group User object ''' def getUserId(self, user): if user is not None: return user.id return None ''' @param user User object @param sshkey_name Name of the ssh key ''' def sshKeyExists(self, user, sshkey_name): keyList = map(lambda k: k.title, user.keys.list()) return sshkey_name in keyList ''' @param user User object @param sshkey Dict containing sshkey infos {"name": "", "file": ""} ''' def addSshKeyToUser(self, user, sshkey): if not self.sshKeyExists(user, sshkey['name']): if self._module.check_mode: return True try: user.keys.create({ 'title': sshkey['name'], 'key': sshkey['file']}) except gitlab.exceptions.GitlabCreateError as e: self._module.fail_json(msg="Failed to assign sshkey to user: %s" % to_native(e)) return True return False ''' @param group Group object @param user_id Id of the user to find ''' def findMember(self, group, user_id): try: member = group.members.get(user_id) except gitlab.exceptions.GitlabGetError as e: return None return member ''' @param group Group object @param user_id Id of the user to check ''' def memberExists(self, group, user_id): member = self.findMember(group, user_id) return member is not None ''' @param group Group object @param user_id Id of the user to check @param access_level GitLab access_level to check ''' def memberAsGoodAccessLevel(self, group, user_id, access_level): member = self.findMember(group, user_id) return member.access_level == access_level ''' @param user User object @param group_path Complete path of the Group including parent group path. <parent_path>/<group_path> @param access_level GitLab access_level to assign ''' def assignUserToGroup(self, user, group_identifier, access_level): group = findGroup(self._gitlab, group_identifier) if self._module.check_mode: return True if group is None: return False if self.memberExists(group, self.getUserId(user)): member = self.findMember(group, self.getUserId(user)) if not self.memberAsGoodAccessLevel(group, member.id, self.ACCESS_LEVEL[access_level]): member.access_level = self.ACCESS_LEVEL[access_level] member.save() return True else: try: group.members.create({ 'user_id': self.getUserId(user), 'access_level': self.ACCESS_LEVEL[access_level]}) except gitlab.exceptions.GitlabCreateError as e: self._module.fail_json(msg="Failed to assign user to group: %s" % to_native(e)) return True return False ''' @param user User object @param arguments User attributes ''' def updateUser(self, user, arguments): changed = False for arg_key, arg_value in arguments.items(): if arguments[arg_key] is not None: if getattr(user, arg_key) != arguments[arg_key]: setattr(user, arg_key, arguments[arg_key]) changed = True return (changed, user) ''' @param arguments User attributes ''' def createUser(self, arguments): if self._module.check_mode: return True try: user = self._gitlab.users.create(arguments) except (gitlab.exceptions.GitlabCreateError) as e: self._module.fail_json(msg="Failed to create user: %s " % to_native(e)) return user ''' @param username Username of the user ''' def findUser(self, username): users = self._gitlab.users.list(search=username) for user in users: if (user.username == username): return user ''' @param username Username of the user ''' def existsUser(self, username): # When user exists, object will be stored in self.userObject. user = self.findUser(username) if user: self.userObject = user return True return False def deleteUser(self): if self._module.check_mode: return True user = self.userObject return user.delete() def deprecation_warning(module): deprecated_aliases = ['login_token'] for aliase in deprecated_aliases: if aliase in module.params: module.deprecate("Alias \'{aliase}\' is deprecated".format(aliase=aliase), "2.10") def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), name=dict(type='str', required=True), state=dict(type='str', default="present", choices=["absent", "present"]), username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), email=dict(type='str', required=True), sshkey_name=dict(type='str'), sshkey_file=dict(type='str'), group=dict(type='str'), access_level=dict(type='str', default="guest", choices=["developer", "guest", "maintainer", "master", "owner", "reporter"]), confirm=dict(type='bool', default=True), isadmin=dict(type='bool', default=False), external=dict(type='bool', default=False), )) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[ ['api_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token'] ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[ ['api_username', 'api_token', 'login_user', 'login_token'], ['server_url', 'api_url'] ], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] user_name = module.params['name'] state = module.params['state'] user_username = module.params['username'].lower() user_password = module.params['password'] user_email = module.params['email'] user_sshkey_name = module.params['sshkey_name'] user_sshkey_file = module.params['sshkey_file'] group_path = module.params['group'] access_level = module.params['access_level'] confirm = module.params['confirm'] user_isadmin = module.params['isadmin'] user_external = module.params['external'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) gitlab_user = GitLabUser(module, gitlab_instance) user_exists = gitlab_user.existsUser(user_username) if state == 'absent': if user_exists: gitlab_user.deleteUser() module.exit_json(changed=True, msg="Successfully deleted user %s" % user_username) else: module.exit_json(changed=False, msg="User deleted or does not exists") if state == 'present': if gitlab_user.createOrUpdateUser(user_username, { "name": user_name, "password": user_password, "email": user_email, "sshkey_name": user_sshkey_name, "sshkey_file": user_sshkey_file, "group_path": group_path, "access_level": access_level, "confirm": confirm, "isadmin": user_isadmin, "external": user_external}): module.exit_json(changed=True, msg="Successfully created or updated the user %s" % user_username, user=gitlab_user.userObject._attrs) else: module.exit_json(changed=False, msg="No need to update the user %s" % user_username, user=gitlab_user.userObject._attrs) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,449
zabbix_host: cannot update host with port set to usermacro
##### SUMMARY If a host has port set to a usermacro, the host is created successfully. On the next run, the update fails with `ValueError: invalid literal for int() with base 10: {$MACRO}`. Tested with the latest `zabbix_host` from git. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME zabbix_host ##### ANSIBLE VERSION latest ##### CONFIGURATION Not relevant. ##### OS / ENVIRONMENT Not relevant. ##### STEPS TO REPRODUCE Have a host definition with usermacro used for port in an interface. Create the host via Ansible, then run the playbook again. ##### EXPECTED RESULTS Success (reported as no change). ##### ACTUAL RESULTS ```paste below Traceback (most recent call last): File \"/home/ansible/.ansible/tmp/ansible-tmp-1571042967.61-236562069605480/AnsiballZ_zabbix_host.py\", line 114, in <module> _ansiballz_main() File \"/home/ansible/.ansible/tmp/ansible-tmp-1571042967.61-236562069605480/AnsiballZ_zabbix_host.py\", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File \"/home/ansible/.ansible/tmp/ansible-tmp-1571042967.61-236562069605480/AnsiballZ_zabbix_host.py\", line 49, in invoke_module imp.load_module(__main__, mod, module, MOD_DESC) File \"/tmp/ansible_zabbix_host_payload_7ml4r2/__main__.py\", line 857, in <module> File \"/tmp/ansible_zabbix_host_payload_7ml4r2/__main__.py\", line 817, in main File \"/tmp/ansible_zabbix_host_payload_7ml4r2/__main__.py\", line 479, in check_all_properties File \"/tmp/ansible_zabbix_host_payload_7ml4r2/__main__.py\", line 437, in check_interface_properties ValueError: invalid literal for int() with base 10: {$MACRO} ```
https://github.com/ansible/ansible/issues/63449
https://github.com/ansible/ansible/pull/63637
f92c99b4135327629cc2c92995f00102fcf2f681
aa671be28bb6a3b4b597e54af618a5255a074149
2019-10-14T09:02:34Z
python
2019-10-21T10:12:10Z
lib/ansible/modules/monitoring/zabbix/zabbix_host.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013-2014, Epic Games, Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: zabbix_host short_description: Create/update/delete Zabbix hosts description: - This module allows you to create, modify and delete Zabbix host entries and associated group and template data. version_added: "2.0" author: - "Cove (@cove)" - Tony Minfei Ding (!UNKNOWN) - Harrison Gu (@harrisongu) - Werner Dijkerman (@dj-wasabi) - Eike Frost (@eikef) requirements: - "python >= 2.6" - "zabbix-api >= 0.5.3" options: host_name: description: - Name of the host in Zabbix. - I(host_name) is the unique identifier used and cannot be updated using this module. required: true visible_name: description: - Visible name of the host in Zabbix. version_added: '2.3' description: description: - Description of the host in Zabbix. version_added: '2.5' host_groups: description: - List of host groups the host is part of. link_templates: description: - List of templates linked to the host. inventory_mode: description: - Configure the inventory mode. choices: ['automatic', 'manual', 'disabled'] version_added: '2.1' inventory_zabbix: description: - Add Facts for a zabbix inventory (e.g. Tag) (see example below). - Please review the interface documentation for more information on the supported properties - U(https://www.zabbix.com/documentation/3.2/manual/api/reference/host/object#host_inventory) version_added: '2.5' status: description: - Monitoring status of the host. choices: ['enabled', 'disabled'] default: 'enabled' state: description: - State of the host. - On C(present), it will create if host does not exist or update the host if the associated data is different. - On C(absent) will remove a host if it exists. choices: ['present', 'absent'] default: 'present' proxy: description: - The name of the Zabbix proxy to be used. interfaces: type: list description: - List of interfaces to be created for the host (see example below). - For more information, review host interface documentation at - U(https://www.zabbix.com/documentation/4.0/manual/api/reference/hostinterface/object) suboptions: type: description: - Interface type to add - Numerical values are also accepted for interface type - 1 = agent - 2 = snmp - 3 = ipmi - 4 = jmx choices: ['agent', 'snmp', 'ipmi', 'jmx'] required: true main: type: int description: - Whether the interface is used as default. - If multiple interfaces with the same type are provided, only one can be default. - 0 (not default), 1 (default) default: 0 choices: [0, 1] useip: type: int description: - Connect to host interface with IP address instead of DNS name. - 0 (don't use ip), 1 (use ip) default: 0 choices: [0, 1] ip: type: str description: - IP address used by host interface. - Required if I(useip=1). default: '' dns: type: str description: - DNS name of the host interface. - Required if I(useip=0). default: '' port: type: str description: - Port used by host interface. - If not specified, default port for each type of interface is used - 10050 if I(type='agent') - 161 if I(type='snmp') - 623 if I(type='ipmi') - 12345 if I(type='jmx') bulk: type: int description: - Whether to use bulk SNMP requests. - 0 (don't use bulk requests), 1 (use bulk requests) choices: [0, 1] default: 1 default: [] tls_connect: description: - Specifies what encryption to use for outgoing connections. - Possible values, 1 (no encryption), 2 (PSK), 4 (certificate). - Works only with >= Zabbix 3.0 default: 1 version_added: '2.5' tls_accept: description: - Specifies what types of connections are allowed for incoming connections. - The tls_accept parameter accepts values of 1 to 7 - Possible values, 1 (no encryption), 2 (PSK), 4 (certificate). - Values can be combined. - Works only with >= Zabbix 3.0 default: 1 version_added: '2.5' tls_psk_identity: description: - It is a unique name by which this specific PSK is referred to by Zabbix components - Do not put sensitive information in the PSK identity string, it is transmitted over the network unencrypted. - Works only with >= Zabbix 3.0 version_added: '2.5' tls_psk: description: - PSK value is a hard to guess string of hexadecimal digits. - The preshared key, at least 32 hex digits. Required if either I(tls_connect) or I(tls_accept) has PSK enabled. - Works only with >= Zabbix 3.0 version_added: '2.5' ca_cert: description: - Required certificate issuer. - Works only with >= Zabbix 3.0 version_added: '2.5' aliases: [ tls_issuer ] tls_subject: description: - Required certificate subject. - Works only with >= Zabbix 3.0 version_added: '2.5' ipmi_authtype: description: - IPMI authentication algorithm. - Please review the Host object documentation for more information on the supported properties - 'https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object' - Possible values are, C(0) (none), C(1) (MD2), C(2) (MD5), C(4) (straight), C(5) (OEM), C(6) (RMCP+), with -1 being the API default. - Please note that the Zabbix API will treat absent settings as default when updating any of the I(ipmi_)-options; this means that if you attempt to set any of the four options individually, the rest will be reset to default values. version_added: '2.5' ipmi_privilege: description: - IPMI privilege level. - Please review the Host object documentation for more information on the supported properties - 'https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object' - Possible values are C(1) (callback), C(2) (user), C(3) (operator), C(4) (admin), C(5) (OEM), with C(2) being the API default. - also see the last note in the I(ipmi_authtype) documentation version_added: '2.5' ipmi_username: description: - IPMI username. - also see the last note in the I(ipmi_authtype) documentation version_added: '2.5' ipmi_password: description: - IPMI password. - also see the last note in the I(ipmi_authtype) documentation version_added: '2.5' force: description: - Overwrite the host configuration, even if already present. type: bool default: 'yes' version_added: '2.0' extends_documentation_fragment: - zabbix ''' EXAMPLES = ''' - name: Create a new host or update an existing host's info local_action: module: zabbix_host server_url: http://monitor.example.com login_user: username login_password: password host_name: ExampleHost visible_name: ExampleName description: My ExampleHost Description host_groups: - Example group1 - Example group2 link_templates: - Example template1 - Example template2 status: enabled state: present inventory_mode: manual inventory_zabbix: tag: "{{ your_tag }}" alias: "{{ your_alias }}" notes: "Special Informations: {{ your_informations | default('None') }}" location: "{{ your_location }}" site_rack: "{{ your_site_rack }}" os: "{{ your_os }}" hardware: "{{ your_hardware }}" ipmi_authtype: 2 ipmi_privilege: 4 ipmi_username: username ipmi_password: password interfaces: - type: 1 main: 1 useip: 1 ip: 10.xx.xx.xx dns: "" port: 10050 - type: 4 main: 1 useip: 1 ip: 10.xx.xx.xx dns: "" port: 12345 proxy: a.zabbix.proxy - name: Update an existing host's TLS settings local_action: module: zabbix_host server_url: http://monitor.example.com login_user: username login_password: password host_name: ExampleHost visible_name: ExampleName host_groups: - Example group1 tls_psk_identity: test tls_connect: 2 tls_psk: 123456789abcdef123456789abcdef12 ''' import atexit import copy import traceback try: from zabbix_api import ZabbixAPI HAS_ZABBIX_API = True except ImportError: ZBX_IMP_ERR = traceback.format_exc() HAS_ZABBIX_API = False from ansible.module_utils.basic import AnsibleModule, missing_required_lib class Host(object): def __init__(self, module, zbx): self._module = module self._zapi = zbx # exist host def is_host_exist(self, host_name): result = self._zapi.host.get({'filter': {'host': host_name}}) return result # check if host group exists def check_host_group_exist(self, group_names): for group_name in group_names: result = self._zapi.hostgroup.get({'filter': {'name': group_name}}) if not result: self._module.fail_json(msg="Hostgroup not found: %s" % group_name) return True def get_template_ids(self, template_list): template_ids = [] if template_list is None or len(template_list) == 0: return template_ids for template in template_list: template_list = self._zapi.template.get({'output': 'extend', 'filter': {'host': template}}) if len(template_list) < 1: self._module.fail_json(msg="Template not found: %s" % template) else: template_id = template_list[0]['templateid'] template_ids.append(template_id) return template_ids def add_host(self, host_name, group_ids, status, interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): try: if self._module.check_mode: self._module.exit_json(changed=True) parameters = {'host': host_name, 'interfaces': interfaces, 'groups': group_ids, 'status': status, 'tls_connect': tls_connect, 'tls_accept': tls_accept} if proxy_id: parameters['proxy_hostid'] = proxy_id if visible_name: parameters['name'] = visible_name if tls_psk_identity is not None: parameters['tls_psk_identity'] = tls_psk_identity if tls_psk is not None: parameters['tls_psk'] = tls_psk if tls_issuer is not None: parameters['tls_issuer'] = tls_issuer if tls_subject is not None: parameters['tls_subject'] = tls_subject if description: parameters['description'] = description if ipmi_authtype is not None: parameters['ipmi_authtype'] = ipmi_authtype if ipmi_privilege is not None: parameters['ipmi_privilege'] = ipmi_privilege if ipmi_username is not None: parameters['ipmi_username'] = ipmi_username if ipmi_password is not None: parameters['ipmi_password'] = ipmi_password host_list = self._zapi.host.create(parameters) if len(host_list) >= 1: return host_list['hostids'][0] except Exception as e: self._module.fail_json(msg="Failed to create host %s: %s" % (host_name, e)) def update_host(self, host_name, group_ids, status, host_id, interfaces, exist_interface_list, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): try: if self._module.check_mode: self._module.exit_json(changed=True) parameters = {'hostid': host_id, 'groups': group_ids, 'status': status, 'tls_connect': tls_connect, 'tls_accept': tls_accept} if proxy_id >= 0: parameters['proxy_hostid'] = proxy_id if visible_name: parameters['name'] = visible_name if tls_psk_identity: parameters['tls_psk_identity'] = tls_psk_identity if tls_psk: parameters['tls_psk'] = tls_psk if tls_issuer: parameters['tls_issuer'] = tls_issuer if tls_subject: parameters['tls_subject'] = tls_subject if description: parameters['description'] = description if ipmi_authtype: parameters['ipmi_authtype'] = ipmi_authtype if ipmi_privilege: parameters['ipmi_privilege'] = ipmi_privilege if ipmi_username: parameters['ipmi_username'] = ipmi_username if ipmi_password: parameters['ipmi_password'] = ipmi_password self._zapi.host.update(parameters) interface_list_copy = exist_interface_list if interfaces: for interface in interfaces: flag = False interface_str = interface for exist_interface in exist_interface_list: interface_type = int(interface['type']) exist_interface_type = int(exist_interface['type']) if interface_type == exist_interface_type: # update interface_str['interfaceid'] = exist_interface['interfaceid'] self._zapi.hostinterface.update(interface_str) flag = True interface_list_copy.remove(exist_interface) break if not flag: # add interface_str['hostid'] = host_id self._zapi.hostinterface.create(interface_str) # remove remove_interface_ids = [] for remove_interface in interface_list_copy: interface_id = remove_interface['interfaceid'] remove_interface_ids.append(interface_id) if len(remove_interface_ids) > 0: self._zapi.hostinterface.delete(remove_interface_ids) except Exception as e: self._module.fail_json(msg="Failed to update host %s: %s" % (host_name, e)) def delete_host(self, host_id, host_name): try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.delete([host_id]) except Exception as e: self._module.fail_json(msg="Failed to delete host %s: %s" % (host_name, e)) # get host by host name def get_host_by_host_name(self, host_name): host_list = self._zapi.host.get({'output': 'extend', 'selectInventory': 'extend', 'filter': {'host': [host_name]}}) if len(host_list) < 1: self._module.fail_json(msg="Host not found: %s" % host_name) else: return host_list[0] # get proxyid by proxy name def get_proxyid_by_proxy_name(self, proxy_name): proxy_list = self._zapi.proxy.get({'output': 'extend', 'filter': {'host': [proxy_name]}}) if len(proxy_list) < 1: self._module.fail_json(msg="Proxy not found: %s" % proxy_name) else: return int(proxy_list[0]['proxyid']) # get group ids by group names def get_group_ids_by_group_names(self, group_names): group_ids = [] if self.check_host_group_exist(group_names): group_list = self._zapi.hostgroup.get({'output': 'extend', 'filter': {'name': group_names}}) for group in group_list: group_id = group['groupid'] group_ids.append({'groupid': group_id}) return group_ids # get host templates by host id def get_host_templates_by_host_id(self, host_id): template_ids = [] template_list = self._zapi.template.get({'output': 'extend', 'hostids': host_id}) for template in template_list: template_ids.append(template['templateid']) return template_ids # get host groups by host id def get_host_groups_by_host_id(self, host_id): exist_host_groups = [] host_groups_list = self._zapi.hostgroup.get({'output': 'extend', 'hostids': host_id}) if len(host_groups_list) >= 1: for host_groups_name in host_groups_list: exist_host_groups.append(host_groups_name['name']) return exist_host_groups # check the exist_interfaces whether it equals the interfaces or not def check_interface_properties(self, exist_interface_list, interfaces): interfaces_port_list = [] if interfaces is not None: if len(interfaces) >= 1: for interface in interfaces: interfaces_port_list.append(int(interface['port'])) exist_interface_ports = [] if len(exist_interface_list) >= 1: for exist_interface in exist_interface_list: exist_interface_ports.append(int(exist_interface['port'])) if set(interfaces_port_list) != set(exist_interface_ports): return True for exist_interface in exist_interface_list: exit_interface_port = int(exist_interface['port']) for interface in interfaces: interface_port = int(interface['port']) if interface_port == exit_interface_port: for key in interface.keys(): if str(exist_interface[key]) != str(interface[key]): return True return False # get the status of host by host def get_host_status_by_host(self, host): return host['status'] # check all the properties before link or clear template def check_all_properties(self, host_id, host_groups, status, interfaces, template_ids, exist_interfaces, host, proxy_id, visible_name, description, host_name, inventory_mode, inventory_zabbix, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, tls_connect, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): # get the existing host's groups exist_host_groups = self.get_host_groups_by_host_id(host_id) if set(host_groups) != set(exist_host_groups): return True # get the existing status exist_status = self.get_host_status_by_host(host) if int(status) != int(exist_status): return True # check the exist_interfaces whether it equals the interfaces or not if self.check_interface_properties(exist_interfaces, interfaces): return True # get the existing templates exist_template_ids = self.get_host_templates_by_host_id(host_id) if set(list(template_ids)) != set(exist_template_ids): return True if int(host['proxy_hostid']) != int(proxy_id): return True # Check whether the visible_name has changed; Zabbix defaults to the technical hostname if not set. if visible_name: if host['name'] != visible_name and host['name'] != host_name: return True # Only compare description if it is given as a module parameter if description: if host['description'] != description: return True if inventory_mode: if host['inventory']: if int(host['inventory']['inventory_mode']) != self.inventory_mode_numeric(inventory_mode): return True elif inventory_mode != 'disabled': return True if inventory_zabbix: proposed_inventory = copy.deepcopy(host['inventory']) proposed_inventory.update(inventory_zabbix) if proposed_inventory != host['inventory']: return True if tls_accept is not None and 'tls_accept' in host: if int(host['tls_accept']) != tls_accept: return True if tls_psk_identity is not None and 'tls_psk_identity' in host: if host['tls_psk_identity'] != tls_psk_identity: return True if tls_psk is not None and 'tls_psk' in host: if host['tls_psk'] != tls_psk: return True if tls_issuer is not None and 'tls_issuer' in host: if host['tls_issuer'] != tls_issuer: return True if tls_subject is not None and 'tls_subject' in host: if host['tls_subject'] != tls_subject: return True if tls_connect is not None and 'tls_connect' in host: if int(host['tls_connect']) != tls_connect: return True if ipmi_authtype is not None: if int(host['ipmi_authtype']) != ipmi_authtype: return True if ipmi_privilege is not None: if int(host['ipmi_privilege']) != ipmi_privilege: return True if ipmi_username is not None: if host['ipmi_username'] != ipmi_username: return True if ipmi_password is not None: if host['ipmi_password'] != ipmi_password: return True return False # link or clear template of the host def link_or_clear_template(self, host_id, template_id_list, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): # get host's exist template ids exist_template_id_list = self.get_host_templates_by_host_id(host_id) exist_template_ids = set(exist_template_id_list) template_ids = set(template_id_list) template_id_list = list(template_ids) # get unlink and clear templates templates_clear = exist_template_ids.difference(template_ids) templates_clear_list = list(templates_clear) request_str = {'hostid': host_id, 'templates': template_id_list, 'templates_clear': templates_clear_list, 'tls_connect': tls_connect, 'tls_accept': tls_accept, 'ipmi_authtype': ipmi_authtype, 'ipmi_privilege': ipmi_privilege, 'ipmi_username': ipmi_username, 'ipmi_password': ipmi_password} if tls_psk_identity is not None: request_str['tls_psk_identity'] = tls_psk_identity if tls_psk is not None: request_str['tls_psk'] = tls_psk if tls_issuer is not None: request_str['tls_issuer'] = tls_issuer if tls_subject is not None: request_str['tls_subject'] = tls_subject try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.update(request_str) except Exception as e: self._module.fail_json(msg="Failed to link template to host: %s" % e) def inventory_mode_numeric(self, inventory_mode): if inventory_mode == "automatic": return int(1) elif inventory_mode == "manual": return int(0) elif inventory_mode == "disabled": return int(-1) return inventory_mode # Update the host inventory_mode def update_inventory_mode(self, host_id, inventory_mode): # nothing was set, do nothing if not inventory_mode: return inventory_mode = self.inventory_mode_numeric(inventory_mode) # watch for - https://support.zabbix.com/browse/ZBX-6033 request_str = {'hostid': host_id, 'inventory_mode': inventory_mode} try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.update(request_str) except Exception as e: self._module.fail_json(msg="Failed to set inventory_mode to host: %s" % e) def update_inventory_zabbix(self, host_id, inventory): if not inventory: return request_str = {'hostid': host_id, 'inventory': inventory} try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.host.update(request_str) except Exception as e: self._module.fail_json(msg="Failed to set inventory to host: %s" % e) def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), host_name=dict(type='str', required=True), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), host_groups=dict(type='list', required=False), link_templates=dict(type='list', required=False), status=dict(default="enabled", choices=['enabled', 'disabled']), state=dict(default="present", choices=['present', 'absent']), inventory_mode=dict(required=False, choices=['automatic', 'manual', 'disabled']), ipmi_authtype=dict(type='int', default=None), ipmi_privilege=dict(type='int', default=None), ipmi_username=dict(type='str', required=False, default=None), ipmi_password=dict(type='str', required=False, default=None, no_log=True), tls_connect=dict(type='int', default=1), tls_accept=dict(type='int', default=1), tls_psk_identity=dict(type='str', required=False), tls_psk=dict(type='str', required=False), ca_cert=dict(type='str', required=False, aliases=['tls_issuer']), tls_subject=dict(type='str', required=False), inventory_zabbix=dict(required=False, type='dict'), timeout=dict(type='int', default=10), interfaces=dict(type='list', required=False), force=dict(type='bool', default=True), proxy=dict(type='str', required=False), visible_name=dict(type='str', required=False), description=dict(type='str', required=False) ), supports_check_mode=True ) if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib('zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] host_name = module.params['host_name'] visible_name = module.params['visible_name'] description = module.params['description'] host_groups = module.params['host_groups'] link_templates = module.params['link_templates'] inventory_mode = module.params['inventory_mode'] ipmi_authtype = module.params['ipmi_authtype'] ipmi_privilege = module.params['ipmi_privilege'] ipmi_username = module.params['ipmi_username'] ipmi_password = module.params['ipmi_password'] tls_connect = module.params['tls_connect'] tls_accept = module.params['tls_accept'] tls_psk_identity = module.params['tls_psk_identity'] tls_psk = module.params['tls_psk'] tls_issuer = module.params['ca_cert'] tls_subject = module.params['tls_subject'] inventory_zabbix = module.params['inventory_zabbix'] status = module.params['status'] state = module.params['state'] timeout = module.params['timeout'] interfaces = module.params['interfaces'] force = module.params['force'] proxy = module.params['proxy'] # convert enabled to 0; disabled to 1 status = 1 if status == "disabled" else 0 zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) host = Host(module, zbx) template_ids = [] if link_templates: template_ids = host.get_template_ids(link_templates) group_ids = [] if host_groups: group_ids = host.get_group_ids_by_group_names(host_groups) ip = "" if interfaces: # ensure interfaces are well-formed for interface in interfaces: if 'type' not in interface: module.fail_json(msg="(interface) type needs to be specified for interface '%s'." % interface) interfacetypes = {'agent': 1, 'snmp': 2, 'ipmi': 3, 'jmx': 4} if interface['type'] in interfacetypes.keys(): interface['type'] = interfacetypes[interface['type']] if interface['type'] < 1 or interface['type'] > 4: module.fail_json(msg="Interface type can only be 1-4 for interface '%s'." % interface) if 'useip' not in interface: interface['useip'] = 0 if 'dns' not in interface: if interface['useip'] == 0: module.fail_json(msg="dns needs to be set if useip is 0 on interface '%s'." % interface) interface['dns'] = '' if 'ip' not in interface: if interface['useip'] == 1: module.fail_json(msg="ip needs to be set if useip is 1 on interface '%s'." % interface) interface['ip'] = '' if 'main' not in interface: interface['main'] = 0 if 'port' not in interface: if interface['type'] == 1: interface['port'] = "10050" elif interface['type'] == 2: interface['port'] = "161" elif interface['type'] == 3: interface['port'] = "623" elif interface['type'] == 4: interface['port'] = "12345" if interface['type'] == 1: ip = interface['ip'] # Use proxy specified, or set to 0 if proxy: proxy_id = host.get_proxyid_by_proxy_name(proxy) else: proxy_id = 0 # check if host exist is_host_exist = host.is_host_exist(host_name) if is_host_exist: # get host id by host name zabbix_host_obj = host.get_host_by_host_name(host_name) host_id = zabbix_host_obj['hostid'] # If proxy is not specified as a module parameter, use the existing setting if proxy is None: proxy_id = int(zabbix_host_obj['proxy_hostid']) if state == "absent": # remove host host.delete_host(host_id, host_name) module.exit_json(changed=True, result="Successfully delete host %s" % host_name) else: if not host_groups: # if host_groups have not been specified when updating an existing host, just # get the group_ids from the existing host without updating them. host_groups = host.get_host_groups_by_host_id(host_id) group_ids = host.get_group_ids_by_group_names(host_groups) # get existing host's interfaces exist_interfaces = host._zapi.hostinterface.get({'output': 'extend', 'hostids': host_id}) # if no interfaces were specified with the module, start with an empty list if not interfaces: interfaces = [] # When force=no is specified, append existing interfaces to interfaces to update. When # no interfaces have been specified, copy existing interfaces as specified from the API. # Do the same with templates and host groups. if not force or not interfaces: for interface in copy.deepcopy(exist_interfaces): # remove values not used during hostinterface.add/update calls for key in tuple(interface.keys()): if key in ['interfaceid', 'hostid', 'bulk']: interface.pop(key, None) for index in interface.keys(): if index in ['useip', 'main', 'type', 'port']: interface[index] = int(interface[index]) if interface not in interfaces: interfaces.append(interface) if not force or link_templates is None: template_ids = list(set(template_ids + host.get_host_templates_by_host_id(host_id))) if not force: for group_id in host.get_group_ids_by_group_names(host.get_host_groups_by_host_id(host_id)): if group_id not in group_ids: group_ids.append(group_id) # update host if host.check_all_properties(host_id, host_groups, status, interfaces, template_ids, exist_interfaces, zabbix_host_obj, proxy_id, visible_name, description, host_name, inventory_mode, inventory_zabbix, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, tls_connect, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password): host.update_host(host_name, group_ids, status, host_id, interfaces, exist_interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.link_or_clear_template(host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.update_inventory_mode(host_id, inventory_mode) host.update_inventory_zabbix(host_id, inventory_zabbix) module.exit_json(changed=True, result="Successfully update host %s (%s) and linked with template '%s'" % (host_name, ip, link_templates)) else: module.exit_json(changed=False) else: if state == "absent": # the host is already deleted. module.exit_json(changed=False) if not group_ids: module.fail_json(msg="Specify at least one group for creating host '%s'." % host_name) if not interfaces or (interfaces and len(interfaces) == 0): module.fail_json(msg="Specify at least one interface for creating host '%s'." % host_name) # create host host_id = host.add_host(host_name, group_ids, status, interfaces, proxy_id, visible_name, description, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.link_or_clear_template(host_id, template_ids, tls_connect, tls_accept, tls_psk_identity, tls_psk, tls_issuer, tls_subject, ipmi_authtype, ipmi_privilege, ipmi_username, ipmi_password) host.update_inventory_mode(host_id, inventory_mode) host.update_inventory_zabbix(host_id, inventory_zabbix) module.exit_json(changed=True, result="Successfully added host %s (%s) and linked with template '%s'" % ( host_name, ip, link_templates)) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
59,078
iam_user module fails to remove an AWS user
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> `iam_user` module fails to remove am AWS user if it has: a group membership, console password (login profile), access keys, MFA device, etc.. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> iam_user ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.2 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/agustin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = .../venv/lib/python3.5/site-packages/ansible executable location =.../venv/bin/ansible python version = 3.5.7 (default, Mar 30 2019, 01:05:18) [GCC 7.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create an AWS user `test` with password or access keys <!--- Paste example playbooks or commands between quotes below --> ```yaml - hosts: localhost tasks: - iam_user: name: test state: absent ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> User's state = absent ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below TASK [iam_user] ************************************************************************************************************************************** An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.DeleteConflictException: An error occurred (DeleteConflict) when calling the DeleteUser operation: Cannot delete entity, must delete login profile first. fatal: [localhost]: FAILED! => {"changed": false, "error": {"code": "DeleteConflict", "message": "Cannot delete entity, must delete login profile first.", "type": "Sender"}, "msg": "Unable to delete user test: An error occurred (DeleteConflict) when calling the DeleteUser operation: Cannot delete entity, must delete login profile first.", "response_metadata": {"http_headers": {"content-length": "300", "content-type": "text/xml", "date": "Sun, 14 Jul 2019 18:34:25 GMT", "x-amzn-requestid": "01da0109-a666-11e9-adeb-83c56b62b76d"}, "http_status_code": 409, "request_id": "01da0109-a666-11e9-adeb-83c56b62b76d", "retry_attempts": 0}} ```
https://github.com/ansible/ansible/issues/59078
https://github.com/ansible/ansible/pull/59079
6046386dba6ed3ce5328cda56bc27ca168b29d4b
f0cadb9843dc2103e7f223052812eed993257653
2019-07-14T18:39:05Z
python
2019-10-21T15:06:05Z
lib/ansible/modules/cloud/amazon/iam_user.py
#!/usr/bin/python # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: iam_user short_description: Manage AWS IAM users description: - Manage AWS IAM users version_added: "2.5" author: Josh Souza (@joshsouza) options: name: description: - The name of the user to create. required: true managed_policy: description: - A list of managed policy ARNs or friendly names to attach to the user. To embed an inline policy, use M(iam_policy). required: false state: description: - Create or remove the IAM user required: true choices: [ 'present', 'absent' ] purge_policy: description: - Detach policies which are not included in managed_policy list required: false default: false type: bool requirements: [ botocore, boto3 ] extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Note: This module does not allow management of groups that users belong to. # Groups should manage their membership directly using `iam_group`, # as users belong to them. # Create a user - iam_user: name: testuser1 state: present # Create a user and attach a managed policy using its ARN - iam_user: name: testuser1 managed_policy: - arn:aws:iam::aws:policy/AmazonSNSFullAccess state: present # Remove all managed policies from an existing user with an empty list - iam_user: name: testuser1 state: present purge_policy: true # Delete the user - iam_user: name: testuser1 state: absent ''' RETURN = ''' user: description: dictionary containing all the user information returned: success type: complex contains: arn: description: the Amazon Resource Name (ARN) specifying the user type: str sample: "arn:aws:iam::1234567890:user/testuser1" create_date: description: the date and time, in ISO 8601 date-time format, when the user was created type: str sample: "2017-02-08T04:36:28+00:00" user_id: description: the stable and unique string identifying the user type: str sample: AGPAIDBWE12NSFINE55TM user_name: description: the friendly name that identifies the user type: str sample: testuser1 path: description: the path to the user type: str sample: / ''' from ansible.module_utils._text import to_native from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import camel_dict_to_snake_dict, ec2_argument_spec, get_aws_connection_info, boto3_conn from ansible.module_utils.ec2 import HAS_BOTO3 import traceback try: from botocore.exceptions import ClientError, ParamValidationError except ImportError: pass # caught by imported HAS_BOTO3 def compare_attached_policies(current_attached_policies, new_attached_policies): # If new_attached_policies is None it means we want to remove all policies if len(current_attached_policies) > 0 and new_attached_policies is None: return False current_attached_policies_arn_list = [] for policy in current_attached_policies: current_attached_policies_arn_list.append(policy['PolicyArn']) if not set(current_attached_policies_arn_list).symmetric_difference(set(new_attached_policies)): return True else: return False def convert_friendly_names_to_arns(connection, module, policy_names): # List comprehension that looks for any policy in the 'policy_names' list # that does not begin with 'arn'. If there aren't any, short circuit. # If there are, translate friendly name to the full arn if not any([not policy.startswith('arn:') for policy in policy_names if policy is not None]): return policy_names allpolicies = {} paginator = connection.get_paginator('list_policies') policies = paginator.paginate().build_full_result()['Policies'] for policy in policies: allpolicies[policy['PolicyName']] = policy['Arn'] allpolicies[policy['Arn']] = policy['Arn'] try: return [allpolicies[policy] for policy in policy_names] except KeyError as e: module.fail_json(msg="Couldn't find policy: " + str(e)) def create_or_update_user(connection, module): params = dict() params['UserName'] = module.params.get('name') managed_policies = module.params.get('managed_policy') purge_policy = module.params.get('purge_policy') changed = False if managed_policies: managed_policies = convert_friendly_names_to_arns(connection, module, managed_policies) # Get user user = get_user(connection, module, params['UserName']) # If user is None, create it if user is None: # Check mode means we would create the user if module.check_mode: module.exit_json(changed=True) try: connection.create_user(**params) changed = True except ClientError as e: module.fail_json(msg="Unable to create user: {0}".format(to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except ParamValidationError as e: module.fail_json(msg="Unable to create user: {0}".format(to_native(e)), exception=traceback.format_exc()) # Manage managed policies current_attached_policies = get_attached_policy_list(connection, module, params['UserName']) if not compare_attached_policies(current_attached_policies, managed_policies): current_attached_policies_arn_list = [] for policy in current_attached_policies: current_attached_policies_arn_list.append(policy['PolicyArn']) # If managed_policies has a single empty element we want to remove all attached policies if purge_policy: # Detach policies not present for policy_arn in list(set(current_attached_policies_arn_list) - set(managed_policies)): changed = True if not module.check_mode: try: connection.detach_user_policy(UserName=params['UserName'], PolicyArn=policy_arn) except ClientError as e: module.fail_json(msg="Unable to detach policy {0} from user {1}: {2}".format( policy_arn, params['UserName'], to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except ParamValidationError as e: module.fail_json(msg="Unable to detach policy {0} from user {1}: {2}".format( policy_arn, params['UserName'], to_native(e)), exception=traceback.format_exc()) # If there are policies to adjust that aren't in the current list, then things have changed # Otherwise the only changes were in purging above if set(managed_policies).difference(set(current_attached_policies_arn_list)): changed = True # If there are policies in managed_policies attach each policy if managed_policies != [None] and not module.check_mode: for policy_arn in managed_policies: try: connection.attach_user_policy(UserName=params['UserName'], PolicyArn=policy_arn) except ClientError as e: module.fail_json(msg="Unable to attach policy {0} to user {1}: {2}".format( policy_arn, params['UserName'], to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except ParamValidationError as e: module.fail_json(msg="Unable to attach policy {0} to user {1}: {2}".format( policy_arn, params['UserName'], to_native(e)), exception=traceback.format_exc()) if module.check_mode: module.exit_json(changed=changed) # Get the user again user = get_user(connection, module, params['UserName']) module.exit_json(changed=changed, iam_user=camel_dict_to_snake_dict(user)) def destroy_user(connection, module): params = dict() params['UserName'] = module.params.get('name') if get_user(connection, module, params['UserName']): # Check mode means we would remove this user if module.check_mode: module.exit_json(changed=True) # Remove any attached policies otherwise deletion fails try: for policy in get_attached_policy_list(connection, module, params['UserName']): connection.detach_user_policy(UserName=params['UserName'], PolicyArn=policy['PolicyArn']) except ClientError as e: module.fail_json(msg="Unable to detach policy {0} from user {1}: {2}".format( policy['PolicyArn'], params['UserName'], to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except ParamValidationError as e: module.fail_json(msg="Unable to detach policy {0} from user {1}: {2}".format( policy['PolicyArn'], params['UserName'], to_native(e)), exception=traceback.format_exc()) try: connection.delete_user(**params) except ClientError as e: module.fail_json(msg="Unable to delete user {0}: {1}".format(params['UserName'], to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except ParamValidationError as e: module.fail_json(msg="Unable to delete user {0}: {1}".format(params['UserName'], to_native(e)), exception=traceback.format_exc()) else: module.exit_json(changed=False) module.exit_json(changed=True) def get_user(connection, module, name): params = dict() params['UserName'] = name try: return connection.get_user(**params) except ClientError as e: if e.response['Error']['Code'] == 'NoSuchEntity': return None else: module.fail_json(msg="Unable to get user {0}: {1}".format(name, to_native(e)), **camel_dict_to_snake_dict(e.response)) def get_attached_policy_list(connection, module, name): try: return connection.list_attached_user_policies(UserName=name)['AttachedPolicies'] except ClientError as e: if e.response['Error']['Code'] == 'NoSuchEntity': return None else: module.fail_json(msg="Unable to get policies for user {0}: {1}".format(name, to_native(e)), **camel_dict_to_snake_dict(e.response)) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( name=dict(required=True, type='str'), managed_policy=dict(default=[], type='list'), state=dict(choices=['present', 'absent'], required=True), purge_policy=dict(default=False, type='bool') ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='iam', region=region, endpoint=ec2_url, **aws_connect_params) state = module.params.get("state") if state == 'present': create_or_update_user(connection, module) else: destroy_user(connection, module) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,687
s3_bucket, aws:kms encryption does not default to default s3 key
##### SUMMARY The documentation states the following: ``` encryption_key_id KMS master key ID to use for the default encryption. This parameter is allowed if encryption is aws:kms. If not specified then it will default to the AWS provided KMS key. ``` However, omitting the variable yields the following: ```{"changed": false, "msg": "encryption is aws:kms but all of the following are missing: encryption_key_id"}``` due to these lines: https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/amazon/s3_bucket.py#L703-L704 . Alternatively, specifying an empty string as key yields the following botocore exception: ``` "error": { "code": "InvalidArgument", "message": "if the default sse algorithm is aws:kms and a KMSMasterKeyID is specified, it must be non-empty", "argument_name": "ApplyServerSideEncryptionByDefault" },``` Specifying any other value will attempt to set the name of the key to that value. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME s3_bucket ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ansible 2.10.0.dev0 config file = /deploy-data/ansible-deploy/ansible.cfg configured module search path = ['/deploy-data/ansible-deploy/library'] ansible python module location = /var/lib/awx/venv/ansible/lib/python3.6/site-packages/ansible executable location = /var/lib/awx/venv/ansible/bin/ansible python version = 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] ``` This also applies to 2.9.0.dev0 ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml - s3_bucket: This errors out because empty strings cannot be used name: "{{ bucket_name }}" region: "{{ region }}" encryption: "aws:kms" encryption_key_id: "" - s3_bucket: This errors out due to the key not being set name: "{{ bucket_name }}" region: "{{ region }}" encryption: "aws:kms" - name: This sets the key used to one named 'False' s3_bucket: name: "{{ bucket_name }}" region: "{{ region }}" encryption: "aws:kms" encryption_key_id: False ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> As per the documented changes, it would be expected that the default S3 KMS would be applied to the bucket. ##### ACTUAL RESULTS See above.
https://github.com/ansible/ansible/issues/61687
https://github.com/ansible/ansible/pull/62031
2e81b813ddfdd0b37c0d5fad34ec061c6f0eb079
aa68f728fdd9b2b93da3da6a6b18a00b24cfe7e3
2019-09-02T14:08:59Z
python
2019-10-21T23:45:41Z
lib/ansible/modules/cloud/amazon/s3_bucket.py
#!/usr/bin/python # # This is a free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This Ansible library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: s3_bucket short_description: Manage S3 buckets in AWS, DigitalOcean, Ceph, Walrus and FakeS3 description: - Manage S3 buckets in AWS, DigitalOcean, Ceph, Walrus and FakeS3 version_added: "2.0" requirements: [ boto3 ] author: "Rob White (@wimnat)" options: force: description: - When trying to delete a bucket, delete all keys (including versions and delete markers) in the bucket first (an s3 bucket must be empty for a successful deletion) type: bool default: 'no' name: description: - Name of the s3 bucket required: true policy: description: - The JSON policy as a string. s3_url: description: - S3 URL endpoint for usage with DigitalOcean, Ceph, Eucalyptus and fakes3 etc. - Assumes AWS if not specified. - For Walrus, use FQDN of the endpoint without scheme nor path. aliases: [ S3_URL ] ceph: description: - Enable API compatibility with Ceph. It takes into account the S3 API subset working with Ceph in order to provide the same module behaviour where possible. type: bool version_added: "2.2" requester_pays: description: - With Requester Pays buckets, the requester instead of the bucket owner pays the cost of the request and the data download from the bucket. type: bool default: False state: description: - Create or remove the s3 bucket required: false default: present choices: [ 'present', 'absent' ] tags: description: - tags dict to apply to bucket purge_tags: description: - whether to remove tags that aren't present in the C(tags) parameter type: bool default: True version_added: "2.9" versioning: description: - Whether versioning is enabled or disabled (note that once versioning is enabled, it can only be suspended) type: bool encryption: description: - Describes the default server-side encryption to apply to new objects in the bucket. In order to remove the server-side encryption, the encryption needs to be set to 'none' explicitly. choices: [ 'none', 'AES256', 'aws:kms' ] version_added: "2.9" encryption_key_id: description: KMS master key ID to use for the default encryption. This parameter is allowed if encryption is aws:kms. If not specified then it will default to the AWS provided KMS key. version_added: "2.9" extends_documentation_fragment: - aws - ec2 notes: - If C(requestPayment), C(policy), C(tagging) or C(versioning) operations/API aren't implemented by the endpoint, module doesn't fail if related parameters I(requester_pays), I(policy), I(tags) or I(versioning) are C(None). ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Create a simple s3 bucket - s3_bucket: name: mys3bucket state: present # Create a simple s3 bucket on Ceph Rados Gateway - s3_bucket: name: mys3bucket s3_url: http://your-ceph-rados-gateway-server.xxx ceph: true # Remove an s3 bucket and any keys it contains - s3_bucket: name: mys3bucket state: absent force: yes # Create a bucket, add a policy from a file, enable requester pays, enable versioning and tag - s3_bucket: name: mys3bucket policy: "{{ lookup('file','policy.json') }}" requester_pays: yes versioning: yes tags: example: tag1 another: tag2 # Create a simple DigitalOcean Spaces bucket using their provided regional endpoint - s3_bucket: name: mydobucket s3_url: 'https://nyc3.digitaloceanspaces.com' ''' import json import os import time from ansible.module_utils.six.moves.urllib.parse import urlparse from ansible.module_utils.six import string_types from ansible.module_utils.basic import to_text from ansible.module_utils.aws.core import AnsibleAWSModule, is_boto3_error_code from ansible.module_utils.ec2 import compare_policies, ec2_argument_spec, boto3_tag_list_to_ansible_dict, ansible_dict_to_boto3_tag_list from ansible.module_utils.ec2 import get_aws_connection_info, boto3_conn, AWSRetry try: from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError, WaiterError except ImportError: pass # handled by AnsibleAWSModule def create_or_update_bucket(s3_client, module, location): policy = module.params.get("policy") name = module.params.get("name") requester_pays = module.params.get("requester_pays") tags = module.params.get("tags") purge_tags = module.params.get("purge_tags") versioning = module.params.get("versioning") encryption = module.params.get("encryption") encryption_key_id = module.params.get("encryption_key_id") changed = False result = {} try: bucket_is_present = bucket_exists(s3_client, name) except EndpointConnectionError as e: module.fail_json_aws(e, msg="Invalid endpoint provided: %s" % to_text(e)) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to check bucket presence") if not bucket_is_present: try: bucket_changed = create_bucket(s3_client, name, location) s3_client.get_waiter('bucket_exists').wait(Bucket=name) changed = changed or bucket_changed except WaiterError as e: module.fail_json_aws(e, msg='An error occurred waiting for the bucket to become available') except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed while creating bucket") # Versioning try: versioning_status = get_bucket_versioning(s3_client, name) except BotoCoreError as exp: module.fail_json_aws(exp, msg="Failed to get bucket versioning") except ClientError as exp: if exp.response['Error']['Code'] != 'NotImplemented' or versioning is not None: module.fail_json_aws(exp, msg="Failed to get bucket versioning") else: if versioning is not None: required_versioning = None if versioning and versioning_status.get('Status') != "Enabled": required_versioning = 'Enabled' elif not versioning and versioning_status.get('Status') == "Enabled": required_versioning = 'Suspended' if required_versioning: try: put_bucket_versioning(s3_client, name, required_versioning) changed = True except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to update bucket versioning") versioning_status = wait_versioning_is_applied(module, s3_client, name, required_versioning) # This output format is there to ensure compatibility with previous versions of the module result['versioning'] = { 'Versioning': versioning_status.get('Status', 'Disabled'), 'MfaDelete': versioning_status.get('MFADelete', 'Disabled'), } # Requester pays try: requester_pays_status = get_bucket_request_payment(s3_client, name) except BotoCoreError as exp: module.fail_json_aws(exp, msg="Failed to get bucket request payment") except ClientError as exp: if exp.response['Error']['Code'] != 'NotImplemented' or requester_pays is not None: module.fail_json_aws(exp, msg="Failed to get bucket request payment") else: if requester_pays: payer = 'Requester' if requester_pays else 'BucketOwner' if requester_pays_status != payer: put_bucket_request_payment(s3_client, name, payer) requester_pays_status = wait_payer_is_applied(module, s3_client, name, payer, should_fail=False) if requester_pays_status is None: # We have seen that it happens quite a lot of times that the put request was not taken into # account, so we retry one more time put_bucket_request_payment(s3_client, name, payer) requester_pays_status = wait_payer_is_applied(module, s3_client, name, payer, should_fail=True) changed = True result['requester_pays'] = requester_pays # Policy try: current_policy = get_bucket_policy(s3_client, name) except BotoCoreError as exp: module.fail_json_aws(exp, msg="Failed to get bucket policy") except ClientError as exp: if exp.response['Error']['Code'] != 'NotImplemented' or policy is not None: module.fail_json_aws(exp, msg="Failed to get bucket policy") else: if policy is not None: if isinstance(policy, string_types): policy = json.loads(policy) if not policy and current_policy: try: delete_bucket_policy(s3_client, name) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to delete bucket policy") current_policy = wait_policy_is_applied(module, s3_client, name, policy) changed = True elif compare_policies(current_policy, policy): try: put_bucket_policy(s3_client, name, policy) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to update bucket policy") current_policy = wait_policy_is_applied(module, s3_client, name, policy, should_fail=False) if current_policy is None: # As for request payement, it happens quite a lot of times that the put request was not taken into # account, so we retry one more time put_bucket_policy(s3_client, name, policy) current_policy = wait_policy_is_applied(module, s3_client, name, policy, should_fail=True) changed = True result['policy'] = current_policy # Tags try: current_tags_dict = get_current_bucket_tags_dict(s3_client, name) except BotoCoreError as exp: module.fail_json_aws(exp, msg="Failed to get bucket tags") except ClientError as exp: if exp.response['Error']['Code'] != 'NotImplemented' or tags is not None: module.fail_json_aws(exp, msg="Failed to get bucket tags") else: if tags is not None: # Tags are always returned as text tags = dict((to_text(k), to_text(v)) for k, v in tags.items()) if not purge_tags: # Ensure existing tags that aren't updated by desired tags remain current_copy = current_tags_dict.copy() current_copy.update(tags) tags = current_copy if current_tags_dict != tags: if tags: try: put_bucket_tagging(s3_client, name, tags) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to update bucket tags") else: if purge_tags: try: delete_bucket_tagging(s3_client, name) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to delete bucket tags") current_tags_dict = wait_tags_are_applied(module, s3_client, name, tags) changed = True result['tags'] = current_tags_dict # Encryption if hasattr(s3_client, "get_bucket_encryption"): try: current_encryption = get_bucket_encryption(s3_client, name) except (ClientError, BotoCoreError) as e: module.fail_json_aws(e, msg="Failed to get bucket encryption") elif encryption is not None: module.fail_json(msg="Using bucket encryption requires botocore version >= 1.7.41") if encryption is not None: current_encryption_algorithm = current_encryption.get('SSEAlgorithm') if current_encryption else None current_encryption_key = current_encryption.get('KMSMasterKeyID') if current_encryption else None if encryption == 'none' and current_encryption_algorithm is not None: try: delete_bucket_encryption(s3_client, name) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to delete bucket encryption") current_encryption = wait_encryption_is_applied(module, s3_client, name, None) changed = True elif encryption != 'none' and (encryption != current_encryption_algorithm) or (encryption == 'aws:kms' and current_encryption_key != encryption_key_id): expected_encryption = {'SSEAlgorithm': encryption} if encryption == 'aws:kms': expected_encryption.update({'KMSMasterKeyID': encryption_key_id}) try: put_bucket_encryption(s3_client, name, expected_encryption) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to set bucket encryption") current_encryption = wait_encryption_is_applied(module, s3_client, name, expected_encryption) changed = True result['encryption'] = current_encryption module.exit_json(changed=changed, name=name, **result) def bucket_exists(s3_client, bucket_name): # head_bucket appeared to be really inconsistent, so we use list_buckets instead, # and loop over all the buckets, even if we know it's less performant :( all_buckets = s3_client.list_buckets(Bucket=bucket_name)['Buckets'] return any(bucket['Name'] == bucket_name for bucket in all_buckets) @AWSRetry.exponential_backoff(max_delay=120) def create_bucket(s3_client, bucket_name, location): try: configuration = {} if location not in ('us-east-1', None): configuration['LocationConstraint'] = location if len(configuration) > 0: s3_client.create_bucket(Bucket=bucket_name, CreateBucketConfiguration=configuration) else: s3_client.create_bucket(Bucket=bucket_name) return True except ClientError as e: error_code = e.response['Error']['Code'] if error_code == 'BucketAlreadyOwnedByYou': # We should never get there since we check the bucket presence before calling the create_or_update_bucket # method. However, the AWS Api sometimes fails to report bucket presence, so we catch this exception return False else: raise e @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def put_bucket_tagging(s3_client, bucket_name, tags): s3_client.put_bucket_tagging(Bucket=bucket_name, Tagging={'TagSet': ansible_dict_to_boto3_tag_list(tags)}) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def put_bucket_policy(s3_client, bucket_name, policy): s3_client.put_bucket_policy(Bucket=bucket_name, Policy=json.dumps(policy)) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def delete_bucket_policy(s3_client, bucket_name): s3_client.delete_bucket_policy(Bucket=bucket_name) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def get_bucket_policy(s3_client, bucket_name): try: current_policy = json.loads(s3_client.get_bucket_policy(Bucket=bucket_name).get('Policy')) except ClientError as e: if e.response['Error']['Code'] == 'NoSuchBucketPolicy': current_policy = None else: raise e return current_policy @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def put_bucket_request_payment(s3_client, bucket_name, payer): s3_client.put_bucket_request_payment(Bucket=bucket_name, RequestPaymentConfiguration={'Payer': payer}) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def get_bucket_request_payment(s3_client, bucket_name): return s3_client.get_bucket_request_payment(Bucket=bucket_name).get('Payer') @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def get_bucket_versioning(s3_client, bucket_name): return s3_client.get_bucket_versioning(Bucket=bucket_name) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def put_bucket_versioning(s3_client, bucket_name, required_versioning): s3_client.put_bucket_versioning(Bucket=bucket_name, VersioningConfiguration={'Status': required_versioning}) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def get_bucket_encryption(s3_client, bucket_name): try: result = s3_client.get_bucket_encryption(Bucket=bucket_name) return result.get('ServerSideEncryptionConfiguration', {}).get('Rules', [])[0].get('ApplyServerSideEncryptionByDefault') except ClientError as e: if e.response['Error']['Code'] == 'ServerSideEncryptionConfigurationNotFoundError': return None else: raise e except (IndexError, KeyError): return None @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def put_bucket_encryption(s3_client, bucket_name, encryption): server_side_encryption_configuration = {'Rules': [{'ApplyServerSideEncryptionByDefault': encryption}]} s3_client.put_bucket_encryption(Bucket=bucket_name, ServerSideEncryptionConfiguration=server_side_encryption_configuration) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def delete_bucket_tagging(s3_client, bucket_name): s3_client.delete_bucket_tagging(Bucket=bucket_name) @AWSRetry.exponential_backoff(max_delay=120, catch_extra_error_codes=['NoSuchBucket']) def delete_bucket_encryption(s3_client, bucket_name): s3_client.delete_bucket_encryption(Bucket=bucket_name) @AWSRetry.exponential_backoff(max_delay=120) def delete_bucket(s3_client, bucket_name): try: s3_client.delete_bucket(Bucket=bucket_name) except ClientError as e: if e.response['Error']['Code'] == 'NoSuchBucket': # This means bucket should have been in a deleting state when we checked it existence # We just ignore the error pass else: raise e def wait_policy_is_applied(module, s3_client, bucket_name, expected_policy, should_fail=True): for dummy in range(0, 12): try: current_policy = get_bucket_policy(s3_client, bucket_name) except (ClientError, BotoCoreError) as e: module.fail_json_aws(e, msg="Failed to get bucket policy") if compare_policies(current_policy, expected_policy): time.sleep(5) else: return current_policy if should_fail: module.fail_json(msg="Bucket policy failed to apply in the expected time") else: return None def wait_payer_is_applied(module, s3_client, bucket_name, expected_payer, should_fail=True): for dummy in range(0, 12): try: requester_pays_status = get_bucket_request_payment(s3_client, bucket_name) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to get bucket request payment") if requester_pays_status != expected_payer: time.sleep(5) else: return requester_pays_status if should_fail: module.fail_json(msg="Bucket request payment failed to apply in the expected time") else: return None def wait_encryption_is_applied(module, s3_client, bucket_name, expected_encryption): for dummy in range(0, 12): try: encryption = get_bucket_encryption(s3_client, bucket_name) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to get updated encryption for bucket") if encryption != expected_encryption: time.sleep(5) else: return encryption module.fail_json(msg="Bucket encryption failed to apply in the expected time") def wait_versioning_is_applied(module, s3_client, bucket_name, required_versioning): for dummy in range(0, 24): try: versioning_status = get_bucket_versioning(s3_client, bucket_name) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to get updated versioning for bucket") if versioning_status.get('Status') != required_versioning: time.sleep(8) else: return versioning_status module.fail_json(msg="Bucket versioning failed to apply in the expected time") def wait_tags_are_applied(module, s3_client, bucket_name, expected_tags_dict): for dummy in range(0, 12): try: current_tags_dict = get_current_bucket_tags_dict(s3_client, bucket_name) except (ClientError, BotoCoreError) as e: module.fail_json_aws(e, msg="Failed to get bucket policy") if current_tags_dict != expected_tags_dict: time.sleep(5) else: return current_tags_dict module.fail_json(msg="Bucket tags failed to apply in the expected time") def get_current_bucket_tags_dict(s3_client, bucket_name): try: current_tags = s3_client.get_bucket_tagging(Bucket=bucket_name).get('TagSet') except ClientError as e: if e.response['Error']['Code'] == 'NoSuchTagSet': return {} raise e return boto3_tag_list_to_ansible_dict(current_tags) def paginated_list(s3_client, **pagination_params): pg = s3_client.get_paginator('list_objects_v2') for page in pg.paginate(**pagination_params): yield [data['Key'] for data in page.get('Contents', [])] def paginated_versions_list(s3_client, **pagination_params): try: pg = s3_client.get_paginator('list_object_versions') for page in pg.paginate(**pagination_params): # We have to merge the Versions and DeleteMarker lists here, as DeleteMarkers can still prevent a bucket deletion yield [(data['Key'], data['VersionId']) for data in (page.get('Versions', []) + page.get('DeleteMarkers', []))] except is_boto3_error_code('NoSuchBucket'): yield [] def destroy_bucket(s3_client, module): force = module.params.get("force") name = module.params.get("name") try: bucket_is_present = bucket_exists(s3_client, name) except EndpointConnectionError as e: module.fail_json_aws(e, msg="Invalid endpoint provided: %s" % to_text(e)) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to check bucket presence") if not bucket_is_present: module.exit_json(changed=False) if force: # if there are contents then we need to delete them (including versions) before we can delete the bucket try: for key_version_pairs in paginated_versions_list(s3_client, Bucket=name): formatted_keys = [{'Key': key, 'VersionId': version} for key, version in key_version_pairs] for fk in formatted_keys: # remove VersionId from cases where they are `None` so that # unversioned objects are deleted using `DeleteObject` # rather than `DeleteObjectVersion`, improving backwards # compatibility with older IAM policies. if not fk.get('VersionId'): fk.pop('VersionId') if formatted_keys: resp = s3_client.delete_objects(Bucket=name, Delete={'Objects': formatted_keys}) if resp.get('Errors'): module.fail_json( msg='Could not empty bucket before deleting. Could not delete objects: {0}'.format( ', '.join([k['Key'] for k in resp['Errors']]) ), errors=resp['Errors'], response=resp ) except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed while deleting bucket") try: delete_bucket(s3_client, name) s3_client.get_waiter('bucket_not_exists').wait(Bucket=name, WaiterConfig=dict(Delay=5, MaxAttempts=60)) except WaiterError as e: module.fail_json_aws(e, msg='An error occurred waiting for the bucket to be deleted.') except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg="Failed to delete bucket") module.exit_json(changed=True) def is_fakes3(s3_url): """ Return True if s3_url has scheme fakes3:// """ if s3_url is not None: return urlparse(s3_url).scheme in ('fakes3', 'fakes3s') else: return False def get_s3_client(module, aws_connect_kwargs, location, ceph, s3_url): if s3_url and ceph: # TODO - test this ceph = urlparse(s3_url) params = dict(module=module, conn_type='client', resource='s3', use_ssl=ceph.scheme == 'https', region=location, endpoint=s3_url, **aws_connect_kwargs) elif is_fakes3(s3_url): fakes3 = urlparse(s3_url) port = fakes3.port if fakes3.scheme == 'fakes3s': protocol = "https" if port is None: port = 443 else: protocol = "http" if port is None: port = 80 params = dict(module=module, conn_type='client', resource='s3', region=location, endpoint="%s://%s:%s" % (protocol, fakes3.hostname, to_text(port)), use_ssl=fakes3.scheme == 'fakes3s', **aws_connect_kwargs) else: params = dict(module=module, conn_type='client', resource='s3', region=location, endpoint=s3_url, **aws_connect_kwargs) return boto3_conn(**params) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( force=dict(default=False, type='bool'), policy=dict(type='json'), name=dict(required=True), requester_pays=dict(default=False, type='bool'), s3_url=dict(aliases=['S3_URL']), state=dict(default='present', choices=['present', 'absent']), tags=dict(type='dict'), purge_tags=dict(type='bool', default=True), versioning=dict(type='bool'), ceph=dict(default=False, type='bool'), encryption=dict(choices=['none', 'AES256', 'aws:kms']), encryption_key_id=dict() ) ) module = AnsibleAWSModule( argument_spec=argument_spec, required_if=[['encryption', 'aws:kms', ['encryption_key_id']]] ) region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) if region in ('us-east-1', '', None): # default to US Standard region location = 'us-east-1' else: # Boto uses symbolic names for locations but region strings will # actually work fine for everything except us-east-1 (US Standard) location = region s3_url = module.params.get('s3_url') ceph = module.params.get('ceph') # allow eucarc environment variables to be used if ansible vars aren't set if not s3_url and 'S3_URL' in os.environ: s3_url = os.environ['S3_URL'] if ceph and not s3_url: module.fail_json(msg='ceph flavour requires s3_url') # Look at s3_url and tweak connection settings # if connecting to Ceph RGW, Walrus or fakes3 if s3_url: for key in ['validate_certs', 'security_token', 'profile_name']: aws_connect_kwargs.pop(key, None) s3_client = get_s3_client(module, aws_connect_kwargs, location, ceph, s3_url) if s3_client is None: # this should never happen module.fail_json(msg='Unknown error, failed to create s3 connection, no information from boto.') state = module.params.get("state") encryption = module.params.get("encryption") encryption_key_id = module.params.get("encryption_key_id") # Parameter validation if encryption_key_id is not None and encryption is None: module.fail_json(msg="You must specify encryption parameter along with encryption_key_id.") elif encryption_key_id is not None and encryption != 'aws:kms': module.fail_json(msg="Only 'aws:kms' is a valid option for encryption parameter when you specify encryption_key_id.") if state == 'present': create_or_update_bucket(s3_client, module, location) elif state == 'absent': destroy_bucket(s3_client, module) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,687
s3_bucket, aws:kms encryption does not default to default s3 key
##### SUMMARY The documentation states the following: ``` encryption_key_id KMS master key ID to use for the default encryption. This parameter is allowed if encryption is aws:kms. If not specified then it will default to the AWS provided KMS key. ``` However, omitting the variable yields the following: ```{"changed": false, "msg": "encryption is aws:kms but all of the following are missing: encryption_key_id"}``` due to these lines: https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/amazon/s3_bucket.py#L703-L704 . Alternatively, specifying an empty string as key yields the following botocore exception: ``` "error": { "code": "InvalidArgument", "message": "if the default sse algorithm is aws:kms and a KMSMasterKeyID is specified, it must be non-empty", "argument_name": "ApplyServerSideEncryptionByDefault" },``` Specifying any other value will attempt to set the name of the key to that value. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME s3_bucket ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ansible 2.10.0.dev0 config file = /deploy-data/ansible-deploy/ansible.cfg configured module search path = ['/deploy-data/ansible-deploy/library'] ansible python module location = /var/lib/awx/venv/ansible/lib/python3.6/site-packages/ansible executable location = /var/lib/awx/venv/ansible/bin/ansible python version = 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] ``` This also applies to 2.9.0.dev0 ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml - s3_bucket: This errors out because empty strings cannot be used name: "{{ bucket_name }}" region: "{{ region }}" encryption: "aws:kms" encryption_key_id: "" - s3_bucket: This errors out due to the key not being set name: "{{ bucket_name }}" region: "{{ region }}" encryption: "aws:kms" - name: This sets the key used to one named 'False' s3_bucket: name: "{{ bucket_name }}" region: "{{ region }}" encryption: "aws:kms" encryption_key_id: False ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> As per the documented changes, it would be expected that the default S3 KMS would be applied to the bucket. ##### ACTUAL RESULTS See above.
https://github.com/ansible/ansible/issues/61687
https://github.com/ansible/ansible/pull/62031
2e81b813ddfdd0b37c0d5fad34ec061c6f0eb079
aa68f728fdd9b2b93da3da6a6b18a00b24cfe7e3
2019-09-02T14:08:59Z
python
2019-10-21T23:45:41Z
test/integration/targets/s3_bucket/tasks/main.yml
--- - block: # ============================================================ - name: set connection information for all tasks set_fact: aws_connection_info: &aws_connection_info aws_access_key: "{{ aws_access_key | default('') }}" aws_secret_key: "{{ aws_secret_key | default('') }}" security_token: "{{ security_token | default('') }}" region: "{{ aws_region | default('') }}" no_log: true # ============================================================ - name: Create simple s3_bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible" state: present <<: *aws_connection_info register: output - assert: that: - output.changed - output.name == '{{ resource_prefix }}-testbucket-ansible' - not output.requester_pays # ============================================================ - name: Try to update the same bucket with the same values s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible" state: present <<: *aws_connection_info register: output - assert: that: - not output.changed - output.name == '{{ resource_prefix }}-testbucket-ansible' - not output.requester_pays # ============================================================ - name: Delete test s3_bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible" state: absent <<: *aws_connection_info register: output - assert: that: - output.changed # ============================================================ - name: Set bucket_name variable to be able to use it in lookup('template') set_fact: bucket_name: "{{ resource_prefix }}-testbucket-ansible-complex" - name: Create more complex s3_bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: yes versioning: yes tags: example: tag1 another: tag2 <<: *aws_connection_info register: output - assert: that: - output.changed - output.name == '{{ resource_prefix }}-testbucket-ansible-complex' - output.requester_pays - output.versioning.MfaDelete == 'Disabled' - output.versioning.Versioning == 'Enabled' - output.tags.example == 'tag1' - output.tags.another == 'tag2' - output.policy.Statement[0].Action == 's3:GetObject' - output.policy.Statement[0].Effect == 'Allow' - output.policy.Statement[0].Principal == '*' - output.policy.Statement[0].Resource == 'arn:aws:s3:::{{ resource_prefix }}-testbucket-ansible-complex/*' - output.policy.Statement[0].Sid == 'AddPerm' # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Try to update the same complex s3_bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: yes versioning: yes tags: example: tag1 another: tag2 <<: *aws_connection_info register: output - assert: that: - not output.changed # ============================================================ - name: Update bucket policy on complex bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy-updated.json') }}" requester_pays: yes versioning: yes tags: example: tag1 another: tag2 <<: *aws_connection_info register: output - assert: that: - output.changed - output.policy.Statement[0].Action == 's3:GetObject' - output.policy.Statement[0].Effect == 'Deny' - output.policy.Statement[0].Principal == '*' - output.policy.Statement[0].Resource == 'arn:aws:s3:::{{ resource_prefix }}-testbucket-ansible-complex/*' - output.policy.Statement[0].Sid == 'AddPerm' # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Update attributes for s3_bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: no versioning: no tags: example: tag1-udpated another: tag2 <<: *aws_connection_info register: output - assert: that: - output.changed - output.name == '{{ resource_prefix }}-testbucket-ansible-complex' - not output.requester_pays - output.versioning.MfaDelete == 'Disabled' - output.versioning.Versioning in ['Suspended', 'Disabled'] - output.tags.example == 'tag1-udpated' - output.tags.another == 'tag2' - output.policy.Statement[0].Action == 's3:GetObject' - output.policy.Statement[0].Effect == 'Allow' - output.policy.Statement[0].Principal == '*' - output.policy.Statement[0].Resource == 'arn:aws:s3:::{{ resource_prefix }}-testbucket-ansible-complex/*' - output.policy.Statement[0].Sid == 'AddPerm' # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Remove a tag for s3_bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: no versioning: no tags: example: tag1-udpated <<: *aws_connection_info register: output - assert: that: - output.changed - output.tags.example == 'tag1-udpated' - "'another' not in output.tags" # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Add a tag for s3_bucket with purge_tags False s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: no versioning: no purge_tags: no tags: anewtag: here <<: *aws_connection_info register: output - assert: that: - output.changed - output.tags.example == 'tag1-udpated' - output.tags.anewtag == 'here' # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Update a tag for s3_bucket with purge_tags False s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: no versioning: no purge_tags: no tags: anewtag: next <<: *aws_connection_info register: output - assert: that: - output.changed - output.tags.example == 'tag1-udpated' - output.tags.anewtag == 'next' # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Pass empty tags dict for s3_bucket with purge_tags False s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: no versioning: no purge_tags: no tags: {} <<: *aws_connection_info register: output - assert: that: - not output.changed - output.tags.example == 'tag1-udpated' - output.tags.anewtag == 'next' # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Do not specify any tag to ensure previous tags are not removed s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: no versioning: no <<: *aws_connection_info register: output - assert: that: - not output.changed - output.tags.example == 'tag1-udpated' # ============================================================ - name: Remove all tags s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: present policy: "{{ lookup('template','policy.json') }}" requester_pays: no versioning: no tags: {} <<: *aws_connection_info register: output - assert: that: - output.changed - output.tags == {} # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 5 - name: Delete complex s3 bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-complex" state: absent <<: *aws_connection_info register: output - assert: that: - output.changed # ============================================================ - name: Create bucket with dot in name s3_bucket: name: "{{ resource_prefix }}.testbucket.ansible" state: present <<: *aws_connection_info register: output - assert: that: - output.changed - output.name == '{{ resource_prefix }}.testbucket.ansible' # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 15 - name: Delete s3_bucket with dot in name s3_bucket: name: "{{ resource_prefix }}.testbucket.ansible" state: absent <<: *aws_connection_info register: output - assert: that: - output.changed # ============================================================ - name: Try to delete a missing bucket (should not fail) s3_bucket: name: "{{ resource_prefix }}-testbucket-ansible-missing" state: absent <<: *aws_connection_info register: output - assert: that: - not output.changed # ============================================================ - name: Create bucket with AES256 encryption enabled s3_bucket: name: "{{ resource_prefix }}-testbucket-encrypt-ansible" state: present encryption: "AES256" <<: *aws_connection_info register: output - assert: that: - output.changed - output.name == '{{ resource_prefix }}-testbucket-encrypt-ansible' - output.encryption - output.encryption.SSEAlgorithm == 'AES256' - name: Update bucket with same encryption config s3_bucket: name: "{{ resource_prefix }}-testbucket-encrypt-ansible" state: present encryption: "AES256" <<: *aws_connection_info register: output - assert: that: - not output.changed - output.encryption - output.encryption.SSEAlgorithm == 'AES256' - name: Disable encryption from bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-encrypt-ansible" state: present encryption: "none" <<: *aws_connection_info register: output - assert: that: - output.changed - not output.encryption # ============================================================ - name: Pause to help with s3 bucket eventual consistency pause: seconds: 10 - name: Delete encryption test s3 bucket s3_bucket: name: "{{ resource_prefix }}-testbucket-encrypt-ansible" state: absent <<: *aws_connection_info register: output - assert: that: - output.changed # ============================================================ always: - name: Ensure all buckets are deleted s3_bucket: name: "{{item}}" state: absent <<: *aws_connection_info ignore_errors: yes with_items: - "{{ resource_prefix }}-testbucket-ansible" - "{{ resource_prefix }}-testbucket-ansible-complex" - "{{ resource_prefix }}.testbucket.ansible" - "{{ resource_prefix }}-testbucket-encrypt-ansible"
closed
ansible/ansible
https://github.com/ansible/ansible
63,156
azure_rm_keyvaultkey_info AttributeError: 'AzureRMKeyVaultKeyInfo' object has no attribute 'vault'
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Attribute error not found when listing deleted keys ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> azure_rm_keyvaultkey_info ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.0rc2 config file = /Users/imjoseangel/Documents/source/sandbox/ansible.cfg configured module search path = ['/Users/imjoseangel/Documents/source/sandbox/library'] ansible python module location = /Users/imjoseangel/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/ansible executable location = /Users/imjoseangel/.pyenv/versions/3.7.4/bin/ansible python version = 3.7.4 (default, Sep 10 2019, 20:21:02) [Clang 10.0.1 (clang-1001.0.46.4)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_SSH_ARGS(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = -o StrictHostKeyChecking=no CACHE_PLUGIN(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = memcached CACHE_PLUGIN_TIMEOUT(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = 86400 DEFAULT_CALLBACK_WHITELIST(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = ['timer', 'profile_tasks'] DEFAULT_FILTER_PLUGIN_PATH(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = ['/Users/imjoseangel/Documents/ DEFAULT_FORKS(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = 25 DEFAULT_GATHERING(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = smart DEFAULT_HASH_BEHAVIOUR(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = merge DEFAULT_HOST_LIST(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = ['/Users/imjoseangel/Documents/source/sa DEFAULT_INTERNAL_POLL_INTERVAL(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = 0.001 DEFAULT_LOOKUP_PLUGIN_PATH(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = ['/Users/imjoseangel/Documents/ DEFAULT_MANAGED_STR(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = This file is managed by Ansible.%n template: {file} date: %Y-%m-%d %H:%M:%S user: {uid} host: {host} DEFAULT_MODULE_PATH(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = ['/Users/imjoseangel/Documents/source/ DEFAULT_POLL_INTERVAL(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = 5 DEFAULT_ROLES_PATH(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = ['/Users/imjoseangel/Documents/source/s DEFAULT_TRANSPORT(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = smart DEFAULT_VAULT_PASSWORD_FILE(env: ANSIBLE_VAULT_PASSWORD_FILE) = /Users/imjoseangel/.ansible_password HOST_KEY_CHECKING(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = False INVENTORY_ENABLED(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = ['generator', 'host_list', 'script', 'ya RETRY_FILES_ENABLED(/Users/imjoseangel/Documents/source/sandbox/ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> MacOS with pyenv ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```json { "ANSIBLE_MODULE_ARGS": { "vault_uri": "https://myvault.vault.azure.net/", "show_deleted_key": "True" } } ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> List of deleted keys on keyvault ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below Traceback (most recent call last): File "library/azure_rm_keyvaultkey_info.py", line 457, in <module> main() File "library/azure_rm_keyvaultkey_info.py", line 453, in main AzureRMKeyVaultKeyInfo() File "library/azure_rm_keyvaultkey_info.py", line 272, in __init__ supports_tags=False) File "/Users/imjoseangel/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/ansible/module_utils/azure_rm_common.py", line 325, in __init__ res = self.exec_module(**self.module.params) File "library/azure_rm_keyvaultkey_info.py", line 293, in exec_module self.results['keys'] = self.list_deleted_keys() File "library/azure_rm_keyvaultkey_info.py", line 437, in list_deleted_keys response = self._client.get_deleted_keys(vault_base_url=self.vault) AttributeError: 'AzureRMKeyVaultKeyInfo' object has no attribute 'vault' ```
https://github.com/ansible/ansible/issues/63156
https://github.com/ansible/ansible/pull/63157
aa68f728fdd9b2b93da3da6a6b18a00b24cfe7e3
4745d4571163d6f25664afb60f47bd8ea0f3e4c4
2019-10-05T06:43:17Z
python
2019-10-22T06:21:25Z
lib/ansible/modules/cloud/azure/azure_rm_keyvaultkey_info.py
#!/usr/bin/python # # Copyright (c) 2019 Yunge Zhu, <[email protected]> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_keyvaultkey_info version_added: "2.9" short_description: Get Azure Key Vault key facts. description: - Get facts of Azure Key Vault key. options: vault_uri: description: - Vault uri where the key stored in. required: True type: str name: description: - Key name. If not set, will list all keys in vault_uri. type: str version: description: - Key version. - Set it to C(current) to show latest version of a key. - Set it to C(all) to list all versions of a key. - Set it to specific version to list specific version of a key. eg. fd2682392a504455b79c90dd04a1bf46 default: current type: str show_deleted_key: description: - Set to true to show deleted keys. Set to False to show not deleted keys. type: bool default: false tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. type: list extends_documentation_fragment: - azure author: - "Yunge Zhu (@yungezz)" ''' EXAMPLES = ''' - name: Get latest version of specific key azure_rm_keyvaultkey_info: vault_uri: "https://myVault.vault.azure.net" name: myKey - name: List all versions of specific key azure_rm_keyvaultkey_info: vault_uri: "https://myVault.vault.azure.net" name: myKey version: all - name: List specific version of specific key azure_rm_keyvaultkey_info: vault_uri: "https://myVault.vault.azure.net" name: myKey version: fd2682392a504455b79c90dd04a1bf46 - name: List all keys in specific key vault azure_rm_keyvaultkey_info: vault_uri: "https://myVault.vault.azure.net" - name: List deleted keys in specific key vault azure_rm_keyvaultkey_info: vault_uri: "https://myVault.vault.azure.net" show_deleted_key: True ''' RETURN = ''' keyvaults: description: List of keys in Azure Key Vault. returned: always type: complex contains: kid: description: Key identifier. returned: always type: str sample: "https://myVault.vault.azure.net/keys/key1/fd2682392a504455b79c90dd04a1bf46" permitted_operations: description: - Permitted operations on the key type: list returned: always sample: encrypt type: description: Key type. type: str returned: always sample: RSA version: description: Key version. type: str returned: always sample: fd2682392a504455b79c90dd04a1bf46 key: description: public part of a key. contains: n: description: RSA modules. type: str e: description: RSA public exponent. type: str crv: description: Elliptic curve name. type: str x: description: X component of an EC public key. type: str y: description: Y component of an EC public key. type: str managed: description: - True if the key's lifetime is managed by key vault. type: bool sample: True tags: description: - Tags of the key. returned: always type: list sample: foo attributes: description: - Key attributes. contains: created: description: - Creation datetime. returned: always type: str sample: "2019-04-25T07:26:49+00:00" not_before: description: - Not before datetime. type: str sample: "2019-04-25T07:26:49+00:00" expires: description: - Expiration datetime. type: str sample: "2019-04-25T07:26:49+00:00" updated: description: - Update datetime. returned: always type: str sample: "2019-04-25T07:26:49+00:00" enabled: description: - Indicate whether the key is enabled. returned: always type: str sample: true recovery_level: description: - Reflects the deletion recovery level currently in effect for keys in the current vault. - If it contains 'Purgeable' the key can be permanently deleted by a privileged user, - Otherwise, only the system can purge the key, at the end of the retention interval. returned: always type: str sample: Purgable ''' from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: from azure.keyvault import KeyVaultClient, KeyVaultId, KeyVaultAuthentication, KeyId from azure.keyvault.models import KeyAttributes, JsonWebKey from azure.common.credentials import ServicePrincipalCredentials from azure.keyvault.models.key_vault_error import KeyVaultErrorException from msrestazure.azure_active_directory import MSIAuthentication except ImportError: # This is handled in azure_rm_common pass def keybundle_to_dict(bundle): return dict( tags=bundle.tags, managed=bundle.managed, attributes=dict( enabled=bundle.attributes.enabled, not_before=bundle.attributes.not_before, expires=bundle.attributes.expires, created=bundle.attributes.created, updated=bundle.attributes.updated, recovery_level=bundle.attributes.recovery_level ), kid=bundle.key.kid, version=KeyVaultId.parse_key_id(bundle.key.kid).version, type=bundle.key.kty, permitted_operations=bundle.key.key_ops, key=dict( n=bundle.key.n if hasattr(bundle.key, 'n') else None, e=bundle.key.e if hasattr(bundle.key, 'e') else None, crv=bundle.key.crv if hasattr(bundle.key, 'crv') else None, x=bundle.key.x if hasattr(bundle.key, 'x') else None, y=bundle.k.y if hasattr(bundle.key, 'y') else None ) ) def deletedkeybundle_to_dict(bundle): keybundle = keybundle_to_dict(bundle) keybundle['recovery_id'] = bundle.recovery_id, keybundle['scheduled_purge_date'] = bundle.scheduled_purge_date, keybundle['deleted_date'] = bundle.deleted_date return keybundle def keyitem_to_dict(keyitem): return dict( kid=keyitem.kid, version=KeyVaultId.parse_key_id(keyitem.kid).version, tags=keyitem.tags, manged=keyitem.managed, attributes=dict( enabled=keyitem.attributes.enabled, not_before=keyitem.attributes.not_before, expires=keyitem.attributes.expires, created=keyitem.attributes.created, updated=keyitem.attributes.updated, recovery_level=keyitem.attributes.recovery_level ) ) def deletedkeyitem_to_dict(keyitem): item = keyitem_to_dict(keyitem) item['recovery_id'] = keyitem.recovery_id, item['scheduled_purge_date'] = keyitem.scheduled_purge_date, item['deleted_date'] = keyitem.deleted_date return item class AzureRMKeyVaultKeyInfo(AzureRMModuleBase): def __init__(self): self.module_arg_spec = dict( version=dict(type='str', default='current'), name=dict(type='str'), vault_uri=dict(type='str', required=True), show_deleted_key=dict(type='bool', default=False), tags=dict(type='list') ) self.vault_uri = None self.name = None self.version = None self.show_deleted_key = False self.tags = None self.results = dict(changed=False) self._client = None super(AzureRMKeyVaultKeyInfo, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=False, supports_tags=False) def exec_module(self, **kwargs): """Main module execution method""" for key in list(self.module_arg_spec.keys()): if hasattr(self, key): setattr(self, key, kwargs[key]) self._client = self.get_keyvault_client() if self.name: if self.show_deleted_key: self.results['keys'] = self.get_deleted_key() else: if self.version == 'all': self.results['keys'] = self.get_key_versions() else: self.results['keys'] = self.get_key() else: if self.show_deleted_key: self.results['keys'] = self.list_deleted_keys() else: self.results['keys'] = self.list_keys() return self.results def get_keyvault_client(self): try: self.log("Get KeyVaultClient from MSI") credentials = MSIAuthentication(resource='https://vault.azure.net') return KeyVaultClient(credentials) except Exception: self.log("Get KeyVaultClient from service principal") # Create KeyVault Client using KeyVault auth class and auth_callback def auth_callback(server, resource, scope): if self.credentials['client_id'] is None or self.credentials['secret'] is None: self.fail('Please specify client_id, secret and tenant to access azure Key Vault.') tenant = self.credentials.get('tenant') if not self.credentials['tenant']: tenant = "common" authcredential = ServicePrincipalCredentials( client_id=self.credentials['client_id'], secret=self.credentials['secret'], tenant=tenant, cloud_environment=self._cloud_environment, resource="https://vault.azure.net") token = authcredential.token return token['token_type'], token['access_token'] return KeyVaultClient(KeyVaultAuthentication(auth_callback)) def get_key(self): ''' Gets the properties of the specified key in key vault. :return: deserialized key state dictionary ''' self.log("Get the key {0}".format(self.name)) results = [] try: if self.version == 'current': response = self._client.get_key(vault_base_url=self.vault_uri, key_name=self.name, key_version='') else: response = self._client.get_key(vault_base_url=self.vault_uri, key_name=self.name, key_version=self.version) if response and self.has_tags(response.tags, self.tags): self.log("Response : {0}".format(response)) results.append(keybundle_to_dict(response)) except KeyVaultErrorException as e: self.log("Did not find the key vault key {0}: {1}".format(self.name, str(e))) return results def get_key_versions(self): ''' Lists keys versions. :return: deserialized versions of key, includes key identifier, attributes and tags ''' self.log("Get the key versions {0}".format(self.name)) results = [] try: response = self._client.get_key_versions(vault_base_url=self.vault_uri, key_name=self.name) self.log("Response : {0}".format(response)) if response: for item in response: if self.has_tags(item.tags, self.tags): results.append(keyitem_to_dict(item)) except KeyVaultErrorException as e: self.log("Did not find key versions {0} : {1}.".format(self.name, str(e))) return results def list_keys(self): ''' Lists keys in specific key vault. :return: deserialized keys, includes key identifier, attributes and tags. ''' self.log("Get the key vaults in current subscription") results = [] try: response = self._client.get_keys(vault_base_url=self.vault_uri) self.log("Response : {0}".format(response)) if response: for item in response: if self.has_tags(item.tags, self.tags): results.append(keyitem_to_dict(item)) except KeyVaultErrorException as e: self.log("Did not find key vault in current subscription {0}.".format(str(e))) return results def get_deleted_key(self): ''' Gets the properties of the specified deleted key in key vault. :return: deserialized key state dictionary ''' self.log("Get the key {0}".format(self.name)) results = [] try: response = self._client.get_deleted_key(vault_base_url=self.vault_uri, key_name=self.name) if response and self.has_tags(response.tags, self.tags): self.log("Response : {0}".format(response)) results.append(deletedkeybundle_to_dict(response)) except KeyVaultErrorException as e: self.log("Did not find the key vault key {0}: {1}".format(self.name, str(e))) return results def list_deleted_keys(self): ''' Lists deleted keys in specific key vault. :return: deserialized keys, includes key identifier, attributes and tags. ''' self.log("Get the key vaults in current subscription") results = [] try: response = self._client.get_deleted_keys(vault_base_url=self.vault) self.log("Response : {0}".format(response)) if response: for item in response: if self.has_tags(item.tags, self.tags): results.append(deletedkeyitem_to_dict(item)) except KeyVaultErrorException as e: self.log("Did not find key vault in current subscription {0}.".format(str(e))) return results def main(): """Main execution""" AzureRMKeyVaultKeyInfo() if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,756
bug in lineinfile when using it with backrefs
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Bug introduced by #63194. Use of lineinfile module along with backrefs fails. Relevant part of code: ``` 336 if index[0] != -1: 337 if backrefs: 338 b_new_line = m.expand(b_line) 339 else: 340 # Don't do backref expansion if not asked. 341 b_new_line = b_line ``` Fixed it by removing lines 338-340, but additional testing required. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lib/ansible/modules/files/lineinfile.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ``` ansible 2.8.6 config file = /home/p/.config/ansible/config.ini configured module search path = ['/home/p/.config/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 3 2019, 10:27:32) [Clang 8.0.1 (tags/RELEASE_801/final)] ``` ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ``` lineinfile: path: "{{ config_elasticsearch }}" regexp: "^#node.name:" line: "node.name: {{ elasticsearch_node }}" backrefs: yes ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ` File \"/usr/local/lib/python3.7/imp.py\", line 169, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 630, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 573, in <module>\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 564, in main\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 338, in present\r\nAttributeError: 'bool' object has no attribute 'expand'\r\n `
https://github.com/ansible/ansible/issues/63756
https://github.com/ansible/ansible/pull/63763
f6c85b738016f803142c57c9256c2af554333d8e
29d4d318a53940ea38d716d9218291d1e2703ab4
2019-10-21T15:03:40Z
python
2019-10-22T14:01:11Z
changelogs/fragments/lineinfile-backrefs-match-object-type.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
63,756
bug in lineinfile when using it with backrefs
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Bug introduced by #63194. Use of lineinfile module along with backrefs fails. Relevant part of code: ``` 336 if index[0] != -1: 337 if backrefs: 338 b_new_line = m.expand(b_line) 339 else: 340 # Don't do backref expansion if not asked. 341 b_new_line = b_line ``` Fixed it by removing lines 338-340, but additional testing required. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lib/ansible/modules/files/lineinfile.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ``` ansible 2.8.6 config file = /home/p/.config/ansible/config.ini configured module search path = ['/home/p/.config/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 3 2019, 10:27:32) [Clang 8.0.1 (tags/RELEASE_801/final)] ``` ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ``` lineinfile: path: "{{ config_elasticsearch }}" regexp: "^#node.name:" line: "node.name: {{ elasticsearch_node }}" backrefs: yes ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ` File \"/usr/local/lib/python3.7/imp.py\", line 169, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 630, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 573, in <module>\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 564, in main\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 338, in present\r\nAttributeError: 'bool' object has no attribute 'expand'\r\n `
https://github.com/ansible/ansible/issues/63756
https://github.com/ansible/ansible/pull/63763
f6c85b738016f803142c57c9256c2af554333d8e
29d4d318a53940ea38d716d9218291d1e2703ab4
2019-10-21T15:03:40Z
python
2019-10-22T14:01:11Z
lib/ansible/modules/files/lineinfile.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Daniel Hokka Zakrisson <[email protected]> # Copyright: (c) 2014, Ahti Kitsik <[email protected]> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: lineinfile short_description: Manage lines in text files description: - This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression. - This is primarily useful when you want to change a single line in a file only. - See the M(replace) module if you want to change multiple, similar lines or check M(blockinfile) if you want to insert/update/remove a block of lines in a file. For other cases, see the M(copy) or M(template) modules. version_added: "0.7" options: path: description: - The file to modify. - Before Ansible 2.3 this option was only usable as I(dest), I(destfile) and I(name). type: path required: true aliases: [ dest, destfile, name ] regexp: description: - The regular expression to look for in every line of the file. - For C(state=present), the pattern to replace if found. Only the last line found will be replaced. - For C(state=absent), the pattern of the line(s) to remove. - If the regular expression is not matched, the line will be added to the file in keeping with C(insertbefore) or C(insertafter) settings. - When modifying a line the regexp should typically match both the initial state of the line as well as its state after replacement by C(line) to ensure idempotence. - Uses Python regular expressions. See U(http://docs.python.org/2/library/re.html). type: str aliases: [ regex ] version_added: '1.7' state: description: - Whether the line should be there or not. type: str choices: [ absent, present ] default: present line: description: - The line to insert/replace into the file. - Required for C(state=present). - If C(backrefs) is set, may contain backreferences that will get expanded with the C(regexp) capture groups if the regexp matches. type: str aliases: [ value ] backrefs: description: - Used with C(state=present). - If set, C(line) can contain backreferences (both positional and named) that will get populated if the C(regexp) matches. - This parameter changes the operation of the module slightly; C(insertbefore) and C(insertafter) will be ignored, and if the C(regexp) does not match anywhere in the file, the file will be left unchanged. - If the C(regexp) does match, the last matching line will be replaced by the expanded line parameter. type: bool default: no version_added: "1.1" insertafter: description: - Used with C(state=present). - If specified, the line will be inserted after the last match of specified regular expression. - If the first match is required, use(firstmatch=yes). - A special value is available; C(EOF) for inserting the line at the end of the file. - If specified regular expression has no matches, EOF will be used instead. - If C(insertbefore) is set, default value C(EOF) will be ignored. - If regular expressions are passed to both C(regexp) and C(insertafter), C(insertafter) is only honored if no match for C(regexp) is found. - May not be used with C(backrefs) or C(insertbefore). type: str choices: [ EOF, '*regex*' ] default: EOF insertbefore: description: - Used with C(state=present). - If specified, the line will be inserted before the last match of specified regular expression. - If the first match is required, use C(firstmatch=yes). - A value is available; C(BOF) for inserting the line at the beginning of the file. - If specified regular expression has no matches, the line will be inserted at the end of the file. - If regular expressions are passed to both C(regexp) and C(insertbefore), C(insertbefore) is only honored if no match for C(regexp) is found. - May not be used with C(backrefs) or C(insertafter). type: str choices: [ BOF, '*regex*' ] version_added: "1.1" create: description: - Used with C(state=present). - If specified, the file will be created if it does not already exist. - By default it will fail if the file is missing. type: bool default: no backup: description: - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. type: bool default: no firstmatch: description: - Used with C(insertafter) or C(insertbefore). - If set, C(insertafter) and C(insertbefore) will work with the first line that matches the given regular expression. type: bool default: no version_added: "2.5" others: description: - All arguments accepted by the M(file) module also work here. type: str extends_documentation_fragment: - files - validate notes: - As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but I(dest) still works as well. seealso: - module: blockinfile - module: copy - module: file - module: replace - module: template - module: win_lineinfile author: - Daniel Hokka Zakrissoni (@dhozac) - Ahti Kitsik (@ahtik) ''' EXAMPLES = r''' # NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path' - name: Ensure SELinux is set to enforcing mode lineinfile: path: /etc/selinux/config regexp: '^SELINUX=' line: SELINUX=enforcing - name: Make sure group wheel is not in the sudoers configuration lineinfile: path: /etc/sudoers state: absent regexp: '^%wheel' - name: Replace a localhost entry with our own lineinfile: path: /etc/hosts regexp: '^127\.0\.0\.1' line: 127.0.0.1 localhost owner: root group: root mode: '0644' - name: Ensure the default Apache port is 8080 lineinfile: path: /etc/httpd/conf/httpd.conf regexp: '^Listen ' insertafter: '^#Listen ' line: Listen 8080 - name: Ensure we have our own comment added to /etc/services lineinfile: path: /etc/services regexp: '^# port for http' insertbefore: '^www.*80/tcp' line: '# port for http by default' - name: Add a line to a file if the file does not exist, without passing regexp lineinfile: path: /tmp/testfile line: 192.168.1.99 foo.lab.net foo create: yes # NOTE: Yaml requires escaping backslashes in double quotes but not in single quotes - name: Ensure the JBoss memory settings are exactly as needed lineinfile: path: /opt/jboss-as/bin/standalone.conf regexp: '^(.*)Xms(\\d+)m(.*)$' line: '\1Xms${xms}m\3' backrefs: yes # NOTE: Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs. - name: Validate the sudoers file before saving lineinfile: path: /etc/sudoers state: present regexp: '^%ADMIN ALL=' line: '%ADMIN ALL=(ALL) NOPASSWD: ALL' validate: /usr/sbin/visudo -cf %s ''' import os import re import tempfile # import module snippets from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native def write_changes(module, b_lines, dest): tmpfd, tmpfile = tempfile.mkstemp() with os.fdopen(tmpfd, 'wb') as f: f.writelines(b_lines) validate = module.params.get('validate', None) valid = not validate if validate: if "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % (validate)) (rc, out, err) = module.run_command(to_bytes(validate % tmpfile, errors='surrogate_or_strict')) valid = rc == 0 if rc != 0: module.fail_json(msg='failed to validate: ' 'rc:%s error:%s' % (rc, err)) if valid: module.atomic_move(tmpfile, to_native(os.path.realpath(to_bytes(dest, errors='surrogate_or_strict')), errors='surrogate_or_strict'), unsafe_writes=module.params['unsafe_writes']) def check_file_attrs(module, changed, message, diff): file_args = module.load_file_common_arguments(module.params) if module.set_fs_attributes_if_different(file_args, False, diff=diff): if changed: message += " and " changed = True message += "ownership, perms or SE linux context changed" return message, changed def present(module, dest, regexp, line, insertafter, insertbefore, create, backup, backrefs, firstmatch): diff = {'before': '', 'after': '', 'before_header': '%s (content)' % dest, 'after_header': '%s (content)' % dest} b_dest = to_bytes(dest, errors='surrogate_or_strict') if not os.path.exists(b_dest): if not create: module.fail_json(rc=257, msg='Destination %s does not exist !' % dest) b_destpath = os.path.dirname(b_dest) if not os.path.exists(b_destpath) and not module.check_mode: try: os.makedirs(b_destpath) except Exception as e: module.fail_json(msg='Error creating %s Error code: %s Error description: %s' % (b_destpath, e[0], e[1])) b_lines = [] else: with open(b_dest, 'rb') as f: b_lines = f.readlines() if module._diff: diff['before'] = to_native(b''.join(b_lines)) if regexp is not None: bre_m = re.compile(to_bytes(regexp, errors='surrogate_or_strict')) if insertafter not in (None, 'BOF', 'EOF'): bre_ins = re.compile(to_bytes(insertafter, errors='surrogate_or_strict')) elif insertbefore not in (None, 'BOF'): bre_ins = re.compile(to_bytes(insertbefore, errors='surrogate_or_strict')) else: bre_ins = None # index[0] is the line num where regexp has been found # index[1] is the line num where insertafter/insertbefore has been found index = [-1, -1] m = None b_line = to_bytes(line, errors='surrogate_or_strict') # The module's doc says # "If regular expressions are passed to both regexp and # insertafter, insertafter is only honored if no match for regexp is found." # Therefore: # 1. regexp was found -> ignore insertafter, replace the founded line # 2. regexp was not found -> insert the line after 'insertafter' or 'insertbefore' line # Given the above: # 1. First check that there is no match for regexp: if regexp is not None: for lineno, b_cur_line in enumerate(b_lines): match_found = bre_m.search(b_cur_line) if match_found: index[0] = lineno m = match_found if firstmatch: break # 2. When no match found on the previous step, # parse for searching insertafter/insertbefore: if not m: for lineno, b_cur_line in enumerate(b_lines): match_found = b_line == b_cur_line.rstrip(b'\r\n') if match_found: index[0] = lineno m = match_found elif bre_ins is not None and bre_ins.search(b_cur_line): if insertafter: # + 1 for the next line index[1] = lineno + 1 if firstmatch: break if insertbefore: # index[1] for the previous line index[1] = lineno if firstmatch: break msg = '' changed = False b_linesep = to_bytes(os.linesep, errors='surrogate_or_strict') # Exact line or Regexp matched a line in the file if index[0] != -1: if backrefs: b_new_line = m.expand(b_line) else: # Don't do backref expansion if not asked. b_new_line = b_line if not b_new_line.endswith(b_linesep): b_new_line += b_linesep # If no regexp was given and no line match is found anywhere in the file, # insert the line appropriately if using insertbefore or insertafter if regexp is None and m is None: # Insert lines if insertafter and insertafter != 'EOF': # Ensure there is a line separator after the found string # at the end of the file. if b_lines and not b_lines[-1][-1:] in (b'\n', b'\r'): b_lines[-1] = b_lines[-1] + b_linesep # If the line to insert after is at the end of the file # use the appropriate index value. if len(b_lines) == index[1]: if b_lines[index[1] - 1].rstrip(b'\r\n') != b_line: b_lines.append(b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[1]].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif insertbefore and insertbefore != 'BOF': # If the line to insert before is at the beginning of the file # use the appropriate index value. if index[1] <= 0: if b_lines[index[1]].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[1] - 1].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[0]] != b_new_line: b_lines[index[0]] = b_new_line msg = 'line replaced' changed = True elif backrefs: # Do absolutely nothing, since it's not safe generating the line # without the regexp matching to populate the backrefs. pass # Add it to the beginning of the file elif insertbefore == 'BOF' or insertafter == 'BOF': b_lines.insert(0, b_line + b_linesep) msg = 'line added' changed = True # Add it to the end of the file if requested or # if insertafter/insertbefore didn't match anything # (so default behaviour is to add at the end) elif insertafter == 'EOF' or index[1] == -1: # If the file is not empty then ensure there's a newline before the added line if b_lines and not b_lines[-1][-1:] in (b'\n', b'\r'): b_lines.append(b_linesep) b_lines.append(b_line + b_linesep) msg = 'line added' changed = True elif insertafter and index[1] != -1: # Don't insert the line if it already matches at the index if b_line != b_lines[index[1]].rstrip(b'\n\r'): b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True # insert matched, but not the regexp else: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True if module._diff: diff['after'] = to_native(b''.join(b_lines)) backupdest = "" if changed and not module.check_mode: if backup and os.path.exists(b_dest): backupdest = module.backup_local(dest) write_changes(module, b_lines, dest) if module.check_mode and not os.path.exists(b_dest): module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=diff) attr_diff = {} msg, changed = check_file_attrs(module, changed, msg, attr_diff) attr_diff['before_header'] = '%s (file attributes)' % dest attr_diff['after_header'] = '%s (file attributes)' % dest difflist = [diff, attr_diff] module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=difflist) def absent(module, dest, regexp, line, backup): b_dest = to_bytes(dest, errors='surrogate_or_strict') if not os.path.exists(b_dest): module.exit_json(changed=False, msg="file not present") msg = '' diff = {'before': '', 'after': '', 'before_header': '%s (content)' % dest, 'after_header': '%s (content)' % dest} with open(b_dest, 'rb') as f: b_lines = f.readlines() if module._diff: diff['before'] = to_native(b''.join(b_lines)) if regexp is not None: bre_c = re.compile(to_bytes(regexp, errors='surrogate_or_strict')) found = [] b_line = to_bytes(line, errors='surrogate_or_strict') def matcher(b_cur_line): if regexp is not None: match_found = bre_c.search(b_cur_line) else: match_found = b_line == b_cur_line.rstrip(b'\r\n') if match_found: found.append(b_cur_line) return not match_found b_lines = [l for l in b_lines if matcher(l)] changed = len(found) > 0 if module._diff: diff['after'] = to_native(b''.join(b_lines)) backupdest = "" if changed and not module.check_mode: if backup: backupdest = module.backup_local(dest) write_changes(module, b_lines, dest) if changed: msg = "%s line(s) removed" % len(found) attr_diff = {} msg, changed = check_file_attrs(module, changed, msg, attr_diff) attr_diff['before_header'] = '%s (file attributes)' % dest attr_diff['after_header'] = '%s (file attributes)' % dest difflist = [diff, attr_diff] module.exit_json(changed=changed, found=len(found), msg=msg, backup=backupdest, diff=difflist) def main(): module = AnsibleModule( argument_spec=dict( path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']), state=dict(type='str', default='present', choices=['absent', 'present']), regexp=dict(type='str', aliases=['regex']), line=dict(type='str', aliases=['value']), insertafter=dict(type='str'), insertbefore=dict(type='str'), backrefs=dict(type='bool', default=False), create=dict(type='bool', default=False), backup=dict(type='bool', default=False), firstmatch=dict(type='bool', default=False), validate=dict(type='str'), ), mutually_exclusive=[['insertbefore', 'insertafter']], add_file_common_args=True, supports_check_mode=True, ) params = module.params create = params['create'] backup = params['backup'] backrefs = params['backrefs'] path = params['path'] firstmatch = params['firstmatch'] regexp = params['regexp'] line = params['line'] if regexp == '': module.warn( "The regular expression is an empty string, which will match every line in the file. " "This may have unintended consequences, such as replacing the last line in the file rather than appending. " "If this is desired, use '^' to match every line in the file and avoid this warning.") b_path = to_bytes(path, errors='surrogate_or_strict') if os.path.isdir(b_path): module.fail_json(rc=256, msg='Path %s is a directory !' % path) if params['state'] == 'present': if backrefs and regexp is None: module.fail_json(msg='regexp is required with backrefs=true') if line is None: module.fail_json(msg='line is required with state=present') # Deal with the insertafter default value manually, to avoid errors # because of the mutually_exclusive mechanism. ins_bef, ins_aft = params['insertbefore'], params['insertafter'] if ins_bef is None and ins_aft is None: ins_aft = 'EOF' present(module, path, regexp, line, ins_aft, ins_bef, create, backup, backrefs, firstmatch) else: if regexp is None and line is None: module.fail_json(msg='one of line or regexp is required with state=absent') absent(module, path, regexp, line, backup) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,756
bug in lineinfile when using it with backrefs
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Bug introduced by #63194. Use of lineinfile module along with backrefs fails. Relevant part of code: ``` 336 if index[0] != -1: 337 if backrefs: 338 b_new_line = m.expand(b_line) 339 else: 340 # Don't do backref expansion if not asked. 341 b_new_line = b_line ``` Fixed it by removing lines 338-340, but additional testing required. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lib/ansible/modules/files/lineinfile.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ``` ansible 2.8.6 config file = /home/p/.config/ansible/config.ini configured module search path = ['/home/p/.config/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 3 2019, 10:27:32) [Clang 8.0.1 (tags/RELEASE_801/final)] ``` ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ``` lineinfile: path: "{{ config_elasticsearch }}" regexp: "^#node.name:" line: "node.name: {{ elasticsearch_node }}" backrefs: yes ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ` File \"/usr/local/lib/python3.7/imp.py\", line 169, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 630, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 573, in <module>\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 564, in main\r\n File \"/tmp/ansible_lineinfile_payload_3mda11zl/__main__.py\", line 338, in present\r\nAttributeError: 'bool' object has no attribute 'expand'\r\n `
https://github.com/ansible/ansible/issues/63756
https://github.com/ansible/ansible/pull/63763
f6c85b738016f803142c57c9256c2af554333d8e
29d4d318a53940ea38d716d9218291d1e2703ab4
2019-10-21T15:03:40Z
python
2019-10-22T14:01:11Z
test/integration/targets/lineinfile/tasks/main.yml
# test code for the lineinfile module # (c) 2014, James Cammarata <[email protected]> # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. - name: deploy the test file for lineinfile copy: src: test.txt dest: "{{ output_dir }}/test.txt" register: result - name: assert that the test file was deployed assert: that: - result is changed - "result.checksum == '5feac65e442c91f557fc90069ce6efc4d346ab51'" - "result.state == 'file'" - name: insert a line at the beginning of the file, and back it up lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line at the beginning" insertbefore: "BOF" backup: yes register: result1 - name: insert a line at the beginning of the file again lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line at the beginning" insertbefore: "BOF" register: result2 - name: assert that the line was inserted at the head of the file assert: that: - result1 is changed - result2 is not changed - result1.msg == 'line added' - result1.backup != '' - name: stat the backup file stat: path: "{{ result1.backup }}" register: result - name: assert the backup file matches the previous hash assert: that: - "result.stat.checksum == '5feac65e442c91f557fc90069ce6efc4d346ab51'" - name: stat the test after the insert at the head stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test hash is what we expect for the file with the insert at the head assert: that: - "result.stat.checksum == '7eade4042b23b800958fe807b5bfc29f8541ec09'" - name: insert a line at the end of the file lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line at the end" insertafter: "EOF" register: result - name: assert that the line was inserted at the end of the file assert: that: - result is changed - "result.msg == 'line added'" - name: stat the test after the insert at the end stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the insert at the end assert: that: - "result.stat.checksum == 'fb57af7dc10a1006061b000f1f04c38e4bef50a9'" - name: insert a line after the first line lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line after line 1" insertafter: "^This is line 1$" register: result - name: assert that the line was inserted after the first line assert: that: - result is changed - "result.msg == 'line added'" - name: stat the test after insert after the first line stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the insert after the first line assert: that: - "result.stat.checksum == '5348da605b1bc93dbadf3a16474cdf22ef975bec'" - name: insert a line before the last line lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line after line 5" insertbefore: "^This is line 5$" register: result - name: assert that the line was inserted before the last line assert: that: - result is changed - "result.msg == 'line added'" - name: stat the test after the insert before the last line stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the insert before the last line assert: that: - "result.stat.checksum == 'e1cae425403507feea4b55bb30a74decfdd4a23e'" - name: replace a line with backrefs lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "This is line 3" backrefs: yes regexp: "^(REF) .* \\1$" register: result - name: assert that the line with backrefs was changed assert: that: - result is changed - "result.msg == 'line replaced'" - name: stat the test after the backref line was replaced stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '2ccdf45d20298f9eaece73b713648e5489a52444'" - name: remove the middle line lineinfile: dest: "{{ output_dir }}/test.txt" state: absent regexp: "^This is line 3$" register: result - name: assert that the line was removed assert: that: - result is changed - "result.msg == '1 line(s) removed'" - name: stat the test after the middle line was removed stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the middle line was removed assert: that: - "result.stat.checksum == 'a6ba6865547c19d4c203c38a35e728d6d1942c75'" - name: run a validation script that succeeds lineinfile: dest: "{{ output_dir }}/test.txt" state: absent regexp: "^This is line 5$" validate: "true %s" register: result - name: assert that the file validated after removing a line assert: that: - result is changed - "result.msg == '1 line(s) removed'" - name: stat the test after the validation succeeded stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the validation succeeded assert: that: - "result.stat.checksum == '76955a4516a00a38aad8427afc9ee3e361024ba5'" - name: run a validation script that fails lineinfile: dest: "{{ output_dir }}/test.txt" state: absent regexp: "^This is line 1$" validate: "/bin/false %s" register: result ignore_errors: yes - name: assert that the validate failed assert: that: - "result.failed == true" - name: stat the test after the validation failed stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches the previous after the validation failed assert: that: - "result.stat.checksum == '76955a4516a00a38aad8427afc9ee3e361024ba5'" - name: use create=yes lineinfile: dest: "{{ output_dir }}/new_test.txt" create: yes insertbefore: BOF state: present line: "This is a new file" register: result - name: assert that the new file was created assert: that: - result is changed - "result.msg == 'line added'" - name: validate that the newly created file exists stat: path: "{{ output_dir }}/new_test.txt" register: result ignore_errors: yes - name: assert the newly created test checksum matches assert: that: - "result.stat.checksum == '038f10f9e31202451b093163e81e06fbac0c6f3a'" # Test EOF in cases where file has no newline at EOF - name: testnoeof deploy the file for lineinfile copy: src: testnoeof.txt dest: "{{ output_dir }}/testnoeof.txt" register: result - name: testnoeof insert a line at the end of the file lineinfile: dest: "{{ output_dir }}/testnoeof.txt" state: present line: "New line at the end" insertafter: "EOF" register: result - name: testempty assert that the line was inserted at the end of the file assert: that: - result is changed - "result.msg == 'line added'" - name: insert a multiple lines at the end of the file lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "This is a line\nwith \\n character" insertafter: "EOF" register: result - name: assert that the multiple lines was inserted assert: that: - result is changed - "result.msg == 'line added'" - name: testnoeof stat the no newline EOF test after the insert at the end stat: path: "{{ output_dir }}/testnoeof.txt" register: result - name: testnoeof assert test checksum matches after the insert at the end assert: that: - "result.stat.checksum == 'f9af7008e3cb67575ce653d094c79cabebf6e523'" # Test EOF with empty file to make sure no unnecessary newline is added - name: testempty deploy the testempty file for lineinfile copy: src: testempty.txt dest: "{{ output_dir }}/testempty.txt" register: result - name: testempty insert a line at the end of the file lineinfile: dest: "{{ output_dir }}/testempty.txt" state: present line: "New line at the end" insertafter: "EOF" register: result - name: testempty assert that the line was inserted at the end of the file assert: that: - result is changed - "result.msg == 'line added'" - name: testempty stat the test after the insert at the end stat: path: "{{ output_dir }}/testempty.txt" register: result - name: testempty assert test checksum matches after the insert at the end assert: that: - "result.stat.checksum == 'f440dc65ea9cec3fd496c1479ddf937e1b949412'" - stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after inserting multiple lines assert: that: - "result.stat.checksum == 'bf5b711f8f0509355aaeb9d0d61e3e82337c1365'" - name: replace a line with backrefs included in the line lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New \\1 created with the backref" backrefs: yes regexp: "^This is (line 4)$" register: result - name: assert that the line with backrefs was changed assert: that: - result is changed - "result.msg == 'line replaced'" - name: stat the test after the backref line was replaced stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '04b7a54d0fb233a4e26c9e625325bb4874841b3c'" ################################################################### # issue 8535 - name: create a new file for testing quoting issues file: dest: "{{ output_dir }}/test_quoting.txt" state: touch register: result - name: assert the new file was created assert: that: - result is changed - name: use with_items to add code-like strings to the quoting txt file lineinfile: dest: "{{ output_dir }}/test_quoting.txt" line: "{{ item }}" insertbefore: BOF with_items: - "'foo'" - "dotenv.load();" - "var dotenv = require('dotenv');" register: result - name: assert the quote test file was modified correctly assert: that: - result.results|length == 3 - result.results[0] is changed - result.results[0].item == "'foo'" - result.results[1] is changed - result.results[1].item == "dotenv.load();" - result.results[2] is changed - result.results[2].item == "var dotenv = require('dotenv');" - name: stat the quote test file stat: path: "{{ output_dir }}/test_quoting.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '7dc3cb033c3971e73af0eaed6623d4e71e5743f1'" - name: insert a line into the quoted file with a single quote lineinfile: dest: "{{ output_dir }}/test_quoting.txt" line: "import g'" register: result - name: assert that the quoted file was changed assert: that: - result is changed - name: stat the quote test file stat: path: "{{ output_dir }}/test_quoting.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '73b271c2cc1cef5663713bc0f00444b4bf9f4543'" - name: insert a line into the quoted file with many double quotation strings lineinfile: dest: "{{ output_dir }}/test_quoting.txt" line: "\"quote\" and \"unquote\"" register: result - name: assert that the quoted file was changed assert: that: - result is changed - name: stat the quote test file stat: path: "{{ output_dir }}/test_quoting.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == 'b10ab2a3c3b6492680c8d0b1d6f35aa6b8f9e731'" ################################################################### # Issue 28721 - name: Deploy the testmultiple file copy: src: testmultiple.txt dest: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the testmultiple file was deployed assert: that: - result is changed - result.checksum == '3e0090a34fb641f3c01e9011546ff586260ea0ea' - result.state == 'file' # Test insertafter - name: Write the same line to a file inserted after different lines lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertafter: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_1 with_items: "{{ test_regexp }}" - name: Assert that the line is added once only assert: that: - _multitest_1.results.0 is changed - _multitest_1.results.1 is not changed - _multitest_1.results.2 is not changed - _multitest_1.results.3 is not changed - name: Do the same thing again to check for changes lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertafter: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_2 with_items: "{{ test_regexp }}" - name: Assert that the line is not added anymore assert: that: - _multitest_2.results.0 is not changed - _multitest_2.results.1 is not changed - _multitest_2.results.2 is not changed - _multitest_2.results.3 is not changed - name: Stat the insertafter file stat: path: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the insertafter file matches expected checksum assert: that: - result.stat.checksum == 'c6733b6c53ddd0e11e6ba39daa556ef8f4840761' # Test insertbefore - name: Deploy the testmultiple file copy: src: testmultiple.txt dest: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the testmultiple file was deployed assert: that: - result is changed - result.checksum == '3e0090a34fb641f3c01e9011546ff586260ea0ea' - result.state == 'file' - name: Write the same line to a file inserted before different lines lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertbefore: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_3 with_items: "{{ test_regexp }}" - name: Assert that the line is added once only assert: that: - _multitest_3.results.0 is changed - _multitest_3.results.1 is not changed - _multitest_3.results.2 is not changed - _multitest_3.results.3 is not changed - name: Do the same thing again to check for changes lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertbefore: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_4 with_items: "{{ test_regexp }}" - name: Assert that the line is not added anymore assert: that: - _multitest_4.results.0 is not changed - _multitest_4.results.1 is not changed - _multitest_4.results.2 is not changed - _multitest_4.results.3 is not changed - name: Stat the insertbefore file stat: path: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the insertbefore file matches expected checksum assert: that: - result.stat.checksum == '5d298651fbc377b45257da10308a9dc2fe1f8be5' ################################################################### # Issue 36156 # Test insertbefore and insertafter with regexp - name: Deploy the test.conf file copy: src: test.conf dest: "{{ output_dir }}/test.conf" register: result - name: Assert that the test.conf file was deployed assert: that: - result is changed - result.checksum == '6037f13e419b132eb3fd20a89e60c6c87a6add38' - result.state == 'file' # Test instertafter - name: Insert lines after with regexp lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertafter: "{{ item.after }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_5 - name: Do the same thing again and check for changes lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertafter: "{{ item.after }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_6 - name: Assert that the file was changed the first time but not the second time assert: that: - item.0 is changed - item.1 is not changed with_together: - "{{ _multitest_5.results }}" - "{{ _multitest_6.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == '06e2c456e5028dd7bcd0b117b5927a1139458c82' - name: Do the same thing a third time without regexp and check for changes lineinfile: path: "{{ output_dir }}/test.conf" line: "{{ item.line }}" insertafter: "{{ item.after }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_7 - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file was changed when no regexp was provided assert: that: - item is not changed with_items: "{{ _multitest_7.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == '06e2c456e5028dd7bcd0b117b5927a1139458c82' # Test insertbefore - name: Deploy the test.conf file copy: src: test.conf dest: "{{ output_dir }}/test.conf" register: result - name: Assert that the test.conf file was deployed assert: that: - result is changed - result.checksum == '6037f13e419b132eb3fd20a89e60c6c87a6add38' - result.state == 'file' - name: Insert lines before with regexp lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertbefore: "{{ item.before }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_8 - name: Do the same thing again and check for changes lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertbefore: "{{ item.before }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_9 - name: Assert that the file was changed the first time but not the second time assert: that: - item.0 is changed - item.1 is not changed with_together: - "{{ _multitest_8.results }}" - "{{ _multitest_9.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == 'c3be9438a07c44d4c256cebfcdbca15a15b1db91' - name: Do the same thing a third time without regexp and check for changes lineinfile: path: "{{ output_dir }}/test.conf" line: "{{ item.line }}" insertbefore: "{{ item.before }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_10 - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file was changed when no regexp was provided assert: that: - item is not changed with_items: "{{ _multitest_10.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == 'c3be9438a07c44d4c256cebfcdbca15a15b1db91' - name: Copy empty file to test with insertbefore copy: src: testempty.txt dest: "{{ output_dir }}/testempty.txt" - name: Add a line to empty file with insertbefore lineinfile: path: "{{ output_dir }}/testempty.txt" line: top insertbefore: '^not in the file$' register: oneline_insbefore_test1 - name: Add a line to file with only one line using insertbefore lineinfile: path: "{{ output_dir }}/testempty.txt" line: top insertbefore: '^not in the file$' register: oneline_insbefore_test2 - name: Stat the file stat: path: "{{ output_dir }}/testempty.txt" register: oneline_insbefore_file - name: Assert that insertebefore worked properly with a one line file assert: that: - oneline_insbefore_test1 is changed - oneline_insbefore_test2 is not changed - oneline_insbefore_file.stat.checksum == '4dca56d05a21f0d018cd311f43e134e4501cf6d9' ################################################################### # Issue 29443 # When using an empty regexp, replace the last line (since it matches every line) # but also provide a warning. - name: Deploy the test file for lineinfile copy: src: test.txt dest: "{{ output_dir }}/test.txt" register: result - name: Assert that the test file was deployed assert: that: - result is changed - result.checksum == '5feac65e442c91f557fc90069ce6efc4d346ab51' - result.state == 'file' - name: Insert a line in the file using an empty string as a regular expression lineinfile: path: "{{ output_dir }}/test.txt" regexp: '' line: This is line 6 register: insert_empty_regexp - name: Stat the file stat: path: "{{ output_dir }}/test.txt" register: result - name: Assert that the file contents match what is expected and a warning was displayed assert: that: - insert_empty_regexp is changed - warning_message in insert_empty_regexp.warnings - result.stat.checksum == '23555a98ceaa88756b4c7c7bba49d9f86eed868f' vars: warning_message: >- The regular expression is an empty string, which will match every line in the file. This may have unintended consequences, such as replacing the last line in the file rather than appending. If this is desired, use '^' to match every line in the file and avoid this warning. ################################################################### ## Issue #58923 ## Using firstmatch with insertafter and ensure multiple lines are not inserted - name: Deploy the firstmatch test file copy: src: firstmatch.txt dest: "{{ output_dir }}/firstmatch.txt" register: result - name: Assert that the test file was deployed assert: that: - result is changed - result.checksum == '1d644e5e2e51c67f1bd12d7bbe2686017f39923d' - result.state == 'file' - name: Insert a line before an existing line using firstmatch lineinfile: path: "{{ output_dir }}/firstmatch.txt" line: INSERT insertafter: line1 firstmatch: yes register: insertafter1 - name: Insert a line before an existing line using firstmatch again lineinfile: path: "{{ output_dir }}/firstmatch.txt" line: INSERT insertafter: line1 firstmatch: yes register: insertafter2 - name: Stat the file stat: path: "{{ output_dir }}/firstmatch.txt" register: result - name: Assert that the file was modified appropriately assert: that: - insertafter1 is changed - insertafter2 is not changed - result.stat.checksum == '114aae024073a3ee8ec8db0ada03c5483326dd86' ######################################################################################## # Tests of fixing the same issue as above (#58923) by @Andersson007 <[email protected]> # and @samdoran <[email protected]>: # Test insertafter with regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' # Regarding the documentation: # If regular expressions are passed to both regexp and # insertafter, insertafter is only honored if no match for regexp is found. # Therefore, # when regular expressions are passed to both regexp and insertafter, then: # 1. regexp was found -> ignore insertafter, replace the founded line # 2. regexp was not found -> insert the line after 'insertafter' line # Regexp is not present in the file, so the line must be inserted after ^#!/bin/sh - name: Add the line using firstmatch, regexp, and insertafter lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test1 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test1_file - name: Add the line using firstmatch, regexp, and insertafter again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test2 # Check of the prev step. # We tried to add the same line with the same playbook, # so nothing has been added: - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test2_file - name: Assert insertafter tests gave the expected results assert: that: - insertafter_test1 is changed - insertafter_test1_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' - insertafter_test2 is not changed - insertafter_test2_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' # Test insertafter without regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' - name: Insert the line using firstmatch and insertafter without regexp lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test3 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test3_file - name: Insert the line using firstmatch and insertafter without regexp again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test4 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test4_file - name: Assert insertafter without regexp tests gave the expected results assert: that: - insertafter_test3 is changed - insertafter_test3_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' - insertafter_test4 is not changed - insertafter_test4_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' # Test insertbefore with regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' - name: Add the line using regexp, firstmatch, and insertbefore lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test1 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test1_file - name: Add the line using regexp, firstmatch, and insertbefore again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test2 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test2_file - name: Assert insertbefore with regexp tests gave the expected results assert: that: - insertbefore_test1 is changed - insertbefore_test1_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' - insertbefore_test2 is not changed - insertbefore_test2_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' # Test insertbefore without regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' - name: Add the line using insertbefore and firstmatch lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test3 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test3_file - name: Add the line using insertbefore and firstmatch again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test4 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test4_file # Test when the line is presented in the file but # not in the before/after spot and it does match the regexp: - name: > Add the line using insertbefore and firstmatch when the regexp line is presented but not close to insertbefore spot lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: ' Darwin\*\) if \[ -z \"\$JAVA_HOME\" \] ; then' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test5 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test5_file - name: Assert insertbefore with regexp tests gave the expected results assert: that: - insertbefore_test3 is changed - insertbefore_test3_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' - insertbefore_test4 is not changed - insertbefore_test4_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' - insertbefore_test5 is not changed - insertbefore_test5_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7'
closed
ansible/ansible
https://github.com/ansible/ansible
63,684
lineinfile crash on 2.8.6
##### SUMMARY With Ansible 2.8.4 the following task worked successfully: ``` - name: "Configure index-url path." lineinfile: path: "{{ pydistutils_cfg_path }}" insertafter: "\\[easy_install\\]" regexp: "^\\s*index-url\\s+=.*$" line: "index-url = {{ nexus_pypi }}" ``` as soon as systems started install Ansible 2.8.6 and attempting to run the same task we started seeing errors like: ``` TASK [install_python : Configure index-url path.] ****************************************************************************************** An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IndexError: list index out of range fatal: [localhost]: FAILED! => { "changed": false, "rc": 1 } MSG: MODULE FAILURE See stdout/stderr for the exact error MODULE_STDERR: Traceback (most recent call last): File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 114, in <module> _ansiballz_main() File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 49, in invoke_module imp.load_module('__main__', mod, module, MOD_DESC) File "/usr/lib/python3.6/imp.py", line 235, in load_module return load_source(name, filename, file) File "/usr/lib/python3.6/imp.py", line 170, in load_source module = _exec(spec, sys.modules[name]) File "<frozen importlib._bootstrap>", line 618, in _exec File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 567, in <module> File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 558, in main File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 413, in present IndexError: list index out of range ``` These look very similar to the #63077 but not quite the same and in a different module. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lineinfile ##### ANSIBLE VERSION ``` testu18@testu18:~$ ansible --version ansible 2.8.6 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/testu18/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ``` testu18@testu18:~$ ansible-config dump --only-changed testu18@testu18:~$ ``` ##### OS / ENVIRONMENT Ubuntu 18.04 and Mac os 10.14.6 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: localhost tasks: - lineinfile: path: "/tmp/somefile" line: "[easy_install]" create: yes - lineinfile: path: "/tmp/somefile" insertafter: "\\[easy_install\\]" regexp: "^\\s*index-url\\s+=.*$" line: "index-url = https://example.org" ``` ##### EXPECTED RESULTS ``` IT-USA-25903:test csalch$ ansible-playbook test_playbook.yml [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************* TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************************************************************************************************************************************** ok: [localhost] TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** changed: [localhost] TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** changed: [localhost] PLAY RECAP *************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` testu18@testu18:~$ ansible-playbook ./test_playbook.yml -vvvv ansible-playbook 2.8.6 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/testu18/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible-playbook python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] Using /etc/ansible/ansible.cfg as config file setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Parsed /etc/ansible/hosts inventory source with ini plugin [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test_playbook.yml ********************************************************************************************************************************************************************************************************************************************************************************************************************************************** Positional arguments: ./test_playbook.yml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) verbosity: 4 connection: smart timeout: 10 1 plays in ./test_playbook.yml PLAY [localhost] ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************* TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:2 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789 `" && echo ansible-tmp-1571406272.54-212983197612789="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/system/setup.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmpkcGtMZ TO /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/ /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/ > /dev/null 2>&1 && sleep 0' ok: [localhost] META: ran handlers TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:4 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449 `" && echo ansible-tmp-1571406273.37-22574126030449="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/files/lineinfile.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmp_GotGN TO /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/ /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/ > /dev/null 2>&1 && sleep 0' ok: [localhost] => { "backup": "", "changed": false, "diff": [ { "after": "", "after_header": "/tmp/somefile (content)", "before": "", "before_header": "/tmp/somefile (content)" }, { "after_header": "/tmp/somefile (file attributes)", "before_header": "/tmp/somefile (file attributes)" } ], "invocation": { "module_args": { "attributes": null, "backrefs": false, "backup": false, "content": null, "create": true, "delimiter": null, "directory_mode": null, "firstmatch": false, "follow": false, "force": null, "group": null, "insertafter": null, "insertbefore": null, "line": "[easy_install]", "mode": null, "owner": null, "path": "/tmp/somefile", "regexp": null, "remote_src": null, "selevel": null, "serole": null, "setype": null, "seuser": null, "src": null, "state": "present", "unsafe_writes": null, "validate": null } }, "msg": "" } TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:9 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258 `" && echo ansible-tmp-1571406273.68-75225899370258="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/files/lineinfile.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmp34bPPv TO /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/ /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 114, in <module> _ansiballz_main() File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 49, in invoke_module imp.load_module('__main__', mod, module, MOD_DESC) File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 567, in <module> File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 558, in main File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 413, in present IndexError: list index out of range fatal: [localhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 114, in <module>\n _ansiballz_main()\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 567, in <module>\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 558, in main\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 413, in present\nIndexError: list index out of range\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } PLAY RECAP *************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** localhost ```
https://github.com/ansible/ansible/issues/63684
https://github.com/ansible/ansible/pull/63696
05c8e33983802cf2f3dd6af6fb2da8a94bc6914d
92cd13a2cff295c7cd5f196c3e30b9db4c9f1c1a
2019-10-18T13:45:17Z
python
2019-10-22T14:39:58Z
changelogs/fragments/lineinfile-use-correct-index-value.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
63,684
lineinfile crash on 2.8.6
##### SUMMARY With Ansible 2.8.4 the following task worked successfully: ``` - name: "Configure index-url path." lineinfile: path: "{{ pydistutils_cfg_path }}" insertafter: "\\[easy_install\\]" regexp: "^\\s*index-url\\s+=.*$" line: "index-url = {{ nexus_pypi }}" ``` as soon as systems started install Ansible 2.8.6 and attempting to run the same task we started seeing errors like: ``` TASK [install_python : Configure index-url path.] ****************************************************************************************** An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IndexError: list index out of range fatal: [localhost]: FAILED! => { "changed": false, "rc": 1 } MSG: MODULE FAILURE See stdout/stderr for the exact error MODULE_STDERR: Traceback (most recent call last): File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 114, in <module> _ansiballz_main() File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 49, in invoke_module imp.load_module('__main__', mod, module, MOD_DESC) File "/usr/lib/python3.6/imp.py", line 235, in load_module return load_source(name, filename, file) File "/usr/lib/python3.6/imp.py", line 170, in load_source module = _exec(spec, sys.modules[name]) File "<frozen importlib._bootstrap>", line 618, in _exec File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 567, in <module> File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 558, in main File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 413, in present IndexError: list index out of range ``` These look very similar to the #63077 but not quite the same and in a different module. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lineinfile ##### ANSIBLE VERSION ``` testu18@testu18:~$ ansible --version ansible 2.8.6 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/testu18/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ``` testu18@testu18:~$ ansible-config dump --only-changed testu18@testu18:~$ ``` ##### OS / ENVIRONMENT Ubuntu 18.04 and Mac os 10.14.6 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: localhost tasks: - lineinfile: path: "/tmp/somefile" line: "[easy_install]" create: yes - lineinfile: path: "/tmp/somefile" insertafter: "\\[easy_install\\]" regexp: "^\\s*index-url\\s+=.*$" line: "index-url = https://example.org" ``` ##### EXPECTED RESULTS ``` IT-USA-25903:test csalch$ ansible-playbook test_playbook.yml [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************* TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************************************************************************************************************************************** ok: [localhost] TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** changed: [localhost] TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** changed: [localhost] PLAY RECAP *************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` testu18@testu18:~$ ansible-playbook ./test_playbook.yml -vvvv ansible-playbook 2.8.6 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/testu18/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible-playbook python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] Using /etc/ansible/ansible.cfg as config file setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Parsed /etc/ansible/hosts inventory source with ini plugin [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test_playbook.yml ********************************************************************************************************************************************************************************************************************************************************************************************************************************************** Positional arguments: ./test_playbook.yml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) verbosity: 4 connection: smart timeout: 10 1 plays in ./test_playbook.yml PLAY [localhost] ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************* TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:2 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789 `" && echo ansible-tmp-1571406272.54-212983197612789="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/system/setup.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmpkcGtMZ TO /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/ /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/ > /dev/null 2>&1 && sleep 0' ok: [localhost] META: ran handlers TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:4 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449 `" && echo ansible-tmp-1571406273.37-22574126030449="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/files/lineinfile.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmp_GotGN TO /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/ /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/ > /dev/null 2>&1 && sleep 0' ok: [localhost] => { "backup": "", "changed": false, "diff": [ { "after": "", "after_header": "/tmp/somefile (content)", "before": "", "before_header": "/tmp/somefile (content)" }, { "after_header": "/tmp/somefile (file attributes)", "before_header": "/tmp/somefile (file attributes)" } ], "invocation": { "module_args": { "attributes": null, "backrefs": false, "backup": false, "content": null, "create": true, "delimiter": null, "directory_mode": null, "firstmatch": false, "follow": false, "force": null, "group": null, "insertafter": null, "insertbefore": null, "line": "[easy_install]", "mode": null, "owner": null, "path": "/tmp/somefile", "regexp": null, "remote_src": null, "selevel": null, "serole": null, "setype": null, "seuser": null, "src": null, "state": "present", "unsafe_writes": null, "validate": null } }, "msg": "" } TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:9 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258 `" && echo ansible-tmp-1571406273.68-75225899370258="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/files/lineinfile.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmp34bPPv TO /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/ /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 114, in <module> _ansiballz_main() File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 49, in invoke_module imp.load_module('__main__', mod, module, MOD_DESC) File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 567, in <module> File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 558, in main File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 413, in present IndexError: list index out of range fatal: [localhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 114, in <module>\n _ansiballz_main()\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 567, in <module>\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 558, in main\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 413, in present\nIndexError: list index out of range\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } PLAY RECAP *************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** localhost ```
https://github.com/ansible/ansible/issues/63684
https://github.com/ansible/ansible/pull/63696
05c8e33983802cf2f3dd6af6fb2da8a94bc6914d
92cd13a2cff295c7cd5f196c3e30b9db4c9f1c1a
2019-10-18T13:45:17Z
python
2019-10-22T14:39:58Z
lib/ansible/modules/files/lineinfile.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Daniel Hokka Zakrisson <[email protected]> # Copyright: (c) 2014, Ahti Kitsik <[email protected]> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: lineinfile short_description: Manage lines in text files description: - This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression. - This is primarily useful when you want to change a single line in a file only. - See the M(replace) module if you want to change multiple, similar lines or check M(blockinfile) if you want to insert/update/remove a block of lines in a file. For other cases, see the M(copy) or M(template) modules. version_added: "0.7" options: path: description: - The file to modify. - Before Ansible 2.3 this option was only usable as I(dest), I(destfile) and I(name). type: path required: true aliases: [ dest, destfile, name ] regexp: description: - The regular expression to look for in every line of the file. - For C(state=present), the pattern to replace if found. Only the last line found will be replaced. - For C(state=absent), the pattern of the line(s) to remove. - If the regular expression is not matched, the line will be added to the file in keeping with C(insertbefore) or C(insertafter) settings. - When modifying a line the regexp should typically match both the initial state of the line as well as its state after replacement by C(line) to ensure idempotence. - Uses Python regular expressions. See U(http://docs.python.org/2/library/re.html). type: str aliases: [ regex ] version_added: '1.7' state: description: - Whether the line should be there or not. type: str choices: [ absent, present ] default: present line: description: - The line to insert/replace into the file. - Required for C(state=present). - If C(backrefs) is set, may contain backreferences that will get expanded with the C(regexp) capture groups if the regexp matches. type: str aliases: [ value ] backrefs: description: - Used with C(state=present). - If set, C(line) can contain backreferences (both positional and named) that will get populated if the C(regexp) matches. - This parameter changes the operation of the module slightly; C(insertbefore) and C(insertafter) will be ignored, and if the C(regexp) does not match anywhere in the file, the file will be left unchanged. - If the C(regexp) does match, the last matching line will be replaced by the expanded line parameter. type: bool default: no version_added: "1.1" insertafter: description: - Used with C(state=present). - If specified, the line will be inserted after the last match of specified regular expression. - If the first match is required, use(firstmatch=yes). - A special value is available; C(EOF) for inserting the line at the end of the file. - If specified regular expression has no matches, EOF will be used instead. - If C(insertbefore) is set, default value C(EOF) will be ignored. - If regular expressions are passed to both C(regexp) and C(insertafter), C(insertafter) is only honored if no match for C(regexp) is found. - May not be used with C(backrefs) or C(insertbefore). type: str choices: [ EOF, '*regex*' ] default: EOF insertbefore: description: - Used with C(state=present). - If specified, the line will be inserted before the last match of specified regular expression. - If the first match is required, use C(firstmatch=yes). - A value is available; C(BOF) for inserting the line at the beginning of the file. - If specified regular expression has no matches, the line will be inserted at the end of the file. - If regular expressions are passed to both C(regexp) and C(insertbefore), C(insertbefore) is only honored if no match for C(regexp) is found. - May not be used with C(backrefs) or C(insertafter). type: str choices: [ BOF, '*regex*' ] version_added: "1.1" create: description: - Used with C(state=present). - If specified, the file will be created if it does not already exist. - By default it will fail if the file is missing. type: bool default: no backup: description: - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. type: bool default: no firstmatch: description: - Used with C(insertafter) or C(insertbefore). - If set, C(insertafter) and C(insertbefore) will work with the first line that matches the given regular expression. type: bool default: no version_added: "2.5" others: description: - All arguments accepted by the M(file) module also work here. type: str extends_documentation_fragment: - files - validate notes: - As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but I(dest) still works as well. seealso: - module: blockinfile - module: copy - module: file - module: replace - module: template - module: win_lineinfile author: - Daniel Hokka Zakrissoni (@dhozac) - Ahti Kitsik (@ahtik) ''' EXAMPLES = r''' # NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path' - name: Ensure SELinux is set to enforcing mode lineinfile: path: /etc/selinux/config regexp: '^SELINUX=' line: SELINUX=enforcing - name: Make sure group wheel is not in the sudoers configuration lineinfile: path: /etc/sudoers state: absent regexp: '^%wheel' - name: Replace a localhost entry with our own lineinfile: path: /etc/hosts regexp: '^127\.0\.0\.1' line: 127.0.0.1 localhost owner: root group: root mode: '0644' - name: Ensure the default Apache port is 8080 lineinfile: path: /etc/httpd/conf/httpd.conf regexp: '^Listen ' insertafter: '^#Listen ' line: Listen 8080 - name: Ensure we have our own comment added to /etc/services lineinfile: path: /etc/services regexp: '^# port for http' insertbefore: '^www.*80/tcp' line: '# port for http by default' - name: Add a line to a file if the file does not exist, without passing regexp lineinfile: path: /tmp/testfile line: 192.168.1.99 foo.lab.net foo create: yes # NOTE: Yaml requires escaping backslashes in double quotes but not in single quotes - name: Ensure the JBoss memory settings are exactly as needed lineinfile: path: /opt/jboss-as/bin/standalone.conf regexp: '^(.*)Xms(\\d+)m(.*)$' line: '\1Xms${xms}m\3' backrefs: yes # NOTE: Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs. - name: Validate the sudoers file before saving lineinfile: path: /etc/sudoers state: present regexp: '^%ADMIN ALL=' line: '%ADMIN ALL=(ALL) NOPASSWD: ALL' validate: /usr/sbin/visudo -cf %s ''' import os import re import tempfile # import module snippets from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native def write_changes(module, b_lines, dest): tmpfd, tmpfile = tempfile.mkstemp() with os.fdopen(tmpfd, 'wb') as f: f.writelines(b_lines) validate = module.params.get('validate', None) valid = not validate if validate: if "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % (validate)) (rc, out, err) = module.run_command(to_bytes(validate % tmpfile, errors='surrogate_or_strict')) valid = rc == 0 if rc != 0: module.fail_json(msg='failed to validate: ' 'rc:%s error:%s' % (rc, err)) if valid: module.atomic_move(tmpfile, to_native(os.path.realpath(to_bytes(dest, errors='surrogate_or_strict')), errors='surrogate_or_strict'), unsafe_writes=module.params['unsafe_writes']) def check_file_attrs(module, changed, message, diff): file_args = module.load_file_common_arguments(module.params) if module.set_fs_attributes_if_different(file_args, False, diff=diff): if changed: message += " and " changed = True message += "ownership, perms or SE linux context changed" return message, changed def present(module, dest, regexp, line, insertafter, insertbefore, create, backup, backrefs, firstmatch): diff = {'before': '', 'after': '', 'before_header': '%s (content)' % dest, 'after_header': '%s (content)' % dest} b_dest = to_bytes(dest, errors='surrogate_or_strict') if not os.path.exists(b_dest): if not create: module.fail_json(rc=257, msg='Destination %s does not exist !' % dest) b_destpath = os.path.dirname(b_dest) if not os.path.exists(b_destpath) and not module.check_mode: try: os.makedirs(b_destpath) except Exception as e: module.fail_json(msg='Error creating %s Error code: %s Error description: %s' % (b_destpath, e[0], e[1])) b_lines = [] else: with open(b_dest, 'rb') as f: b_lines = f.readlines() if module._diff: diff['before'] = to_native(b''.join(b_lines)) if regexp is not None: bre_m = re.compile(to_bytes(regexp, errors='surrogate_or_strict')) if insertafter not in (None, 'BOF', 'EOF'): bre_ins = re.compile(to_bytes(insertafter, errors='surrogate_or_strict')) elif insertbefore not in (None, 'BOF'): bre_ins = re.compile(to_bytes(insertbefore, errors='surrogate_or_strict')) else: bre_ins = None # index[0] is the line num where regexp has been found # index[1] is the line num where insertafter/insertbefore has been found index = [-1, -1] match = None exact_line_match = False b_line = to_bytes(line, errors='surrogate_or_strict') # The module's doc says # "If regular expressions are passed to both regexp and # insertafter, insertafter is only honored if no match for regexp is found." # Therefore: # 1. regexp was found -> ignore insertafter, replace the founded line # 2. regexp was not found -> insert the line after 'insertafter' or 'insertbefore' line # Given the above: # 1. First check that there is no match for regexp: if regexp is not None: for lineno, b_cur_line in enumerate(b_lines): match_found = bre_m.search(b_cur_line) if match_found: index[0] = lineno match = match_found if firstmatch: break # 2. When no match found on the previous step, # parse for searching insertafter/insertbefore: if not match: for lineno, b_cur_line in enumerate(b_lines): if b_line == b_cur_line.rstrip(b'\r\n'): index[0] = lineno exact_line_match = True elif bre_ins is not None and bre_ins.search(b_cur_line): if insertafter: # + 1 for the next line index[1] = lineno + 1 if firstmatch: break if insertbefore: # index[1] for the previous line index[1] = lineno if firstmatch: break msg = '' changed = False b_linesep = to_bytes(os.linesep, errors='surrogate_or_strict') # Exact line or Regexp matched a line in the file if index[0] != -1: if backrefs and match: b_new_line = match.expand(b_line) else: # Don't do backref expansion if not asked. b_new_line = b_line if not b_new_line.endswith(b_linesep): b_new_line += b_linesep # If no regexp was given and no line match is found anywhere in the file, # insert the line appropriately if using insertbefore or insertafter if regexp is None and match is None and not exact_line_match: # Insert lines if insertafter and insertafter != 'EOF': # Ensure there is a line separator after the found string # at the end of the file. if b_lines and not b_lines[-1][-1:] in (b'\n', b'\r'): b_lines[-1] = b_lines[-1] + b_linesep # If the line to insert after is at the end of the file # use the appropriate index value. if len(b_lines) == index[1]: if b_lines[index[1] - 1].rstrip(b'\r\n') != b_line: b_lines.append(b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[1]].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif insertbefore and insertbefore != 'BOF': # If the line to insert before is at the beginning of the file # use the appropriate index value. if index[1] <= 0: if b_lines[index[1]].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[1] - 1].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[0]] != b_new_line: b_lines[index[0]] = b_new_line msg = 'line replaced' changed = True elif backrefs: # Do absolutely nothing, since it's not safe generating the line # without the regexp matching to populate the backrefs. pass # Add it to the beginning of the file elif insertbefore == 'BOF' or insertafter == 'BOF': b_lines.insert(0, b_line + b_linesep) msg = 'line added' changed = True # Add it to the end of the file if requested or # if insertafter/insertbefore didn't match anything # (so default behaviour is to add at the end) elif insertafter == 'EOF' or index[1] == -1: # If the file is not empty then ensure there's a newline before the added line if b_lines and not b_lines[-1][-1:] in (b'\n', b'\r'): b_lines.append(b_linesep) b_lines.append(b_line + b_linesep) msg = 'line added' changed = True elif insertafter and index[1] != -1: # Don't insert the line if it already matches at the index if b_line != b_lines[index[1]].rstrip(b'\n\r'): b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True # insert matched, but not the regexp else: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True if module._diff: diff['after'] = to_native(b''.join(b_lines)) backupdest = "" if changed and not module.check_mode: if backup and os.path.exists(b_dest): backupdest = module.backup_local(dest) write_changes(module, b_lines, dest) if module.check_mode and not os.path.exists(b_dest): module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=diff) attr_diff = {} msg, changed = check_file_attrs(module, changed, msg, attr_diff) attr_diff['before_header'] = '%s (file attributes)' % dest attr_diff['after_header'] = '%s (file attributes)' % dest difflist = [diff, attr_diff] module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=difflist) def absent(module, dest, regexp, line, backup): b_dest = to_bytes(dest, errors='surrogate_or_strict') if not os.path.exists(b_dest): module.exit_json(changed=False, msg="file not present") msg = '' diff = {'before': '', 'after': '', 'before_header': '%s (content)' % dest, 'after_header': '%s (content)' % dest} with open(b_dest, 'rb') as f: b_lines = f.readlines() if module._diff: diff['before'] = to_native(b''.join(b_lines)) if regexp is not None: bre_c = re.compile(to_bytes(regexp, errors='surrogate_or_strict')) found = [] b_line = to_bytes(line, errors='surrogate_or_strict') def matcher(b_cur_line): if regexp is not None: match_found = bre_c.search(b_cur_line) else: match_found = b_line == b_cur_line.rstrip(b'\r\n') if match_found: found.append(b_cur_line) return not match_found b_lines = [l for l in b_lines if matcher(l)] changed = len(found) > 0 if module._diff: diff['after'] = to_native(b''.join(b_lines)) backupdest = "" if changed and not module.check_mode: if backup: backupdest = module.backup_local(dest) write_changes(module, b_lines, dest) if changed: msg = "%s line(s) removed" % len(found) attr_diff = {} msg, changed = check_file_attrs(module, changed, msg, attr_diff) attr_diff['before_header'] = '%s (file attributes)' % dest attr_diff['after_header'] = '%s (file attributes)' % dest difflist = [diff, attr_diff] module.exit_json(changed=changed, found=len(found), msg=msg, backup=backupdest, diff=difflist) def main(): module = AnsibleModule( argument_spec=dict( path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']), state=dict(type='str', default='present', choices=['absent', 'present']), regexp=dict(type='str', aliases=['regex']), line=dict(type='str', aliases=['value']), insertafter=dict(type='str'), insertbefore=dict(type='str'), backrefs=dict(type='bool', default=False), create=dict(type='bool', default=False), backup=dict(type='bool', default=False), firstmatch=dict(type='bool', default=False), validate=dict(type='str'), ), mutually_exclusive=[['insertbefore', 'insertafter']], add_file_common_args=True, supports_check_mode=True, ) params = module.params create = params['create'] backup = params['backup'] backrefs = params['backrefs'] path = params['path'] firstmatch = params['firstmatch'] regexp = params['regexp'] line = params['line'] if regexp == '': module.warn( "The regular expression is an empty string, which will match every line in the file. " "This may have unintended consequences, such as replacing the last line in the file rather than appending. " "If this is desired, use '^' to match every line in the file and avoid this warning.") b_path = to_bytes(path, errors='surrogate_or_strict') if os.path.isdir(b_path): module.fail_json(rc=256, msg='Path %s is a directory !' % path) if params['state'] == 'present': if backrefs and regexp is None: module.fail_json(msg='regexp is required with backrefs=true') if line is None: module.fail_json(msg='line is required with state=present') # Deal with the insertafter default value manually, to avoid errors # because of the mutually_exclusive mechanism. ins_bef, ins_aft = params['insertbefore'], params['insertafter'] if ins_bef is None and ins_aft is None: ins_aft = 'EOF' present(module, path, regexp, line, ins_aft, ins_bef, create, backup, backrefs, firstmatch) else: if regexp is None and line is None: module.fail_json(msg='one of line or regexp is required with state=absent') absent(module, path, regexp, line, backup) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,684
lineinfile crash on 2.8.6
##### SUMMARY With Ansible 2.8.4 the following task worked successfully: ``` - name: "Configure index-url path." lineinfile: path: "{{ pydistutils_cfg_path }}" insertafter: "\\[easy_install\\]" regexp: "^\\s*index-url\\s+=.*$" line: "index-url = {{ nexus_pypi }}" ``` as soon as systems started install Ansible 2.8.6 and attempting to run the same task we started seeing errors like: ``` TASK [install_python : Configure index-url path.] ****************************************************************************************** An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IndexError: list index out of range fatal: [localhost]: FAILED! => { "changed": false, "rc": 1 } MSG: MODULE FAILURE See stdout/stderr for the exact error MODULE_STDERR: Traceback (most recent call last): File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 114, in <module> _ansiballz_main() File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/testu18/.ansible/tmp/ansible-tmp-1571405045.44-114822878223722/AnsiballZ_lineinfile.py", line 49, in invoke_module imp.load_module('__main__', mod, module, MOD_DESC) File "/usr/lib/python3.6/imp.py", line 235, in load_module return load_source(name, filename, file) File "/usr/lib/python3.6/imp.py", line 170, in load_source module = _exec(spec, sys.modules[name]) File "<frozen importlib._bootstrap>", line 618, in _exec File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 567, in <module> File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 558, in main File "/tmp/ansible_lineinfile_payload_iwtwv4dj/__main__.py", line 413, in present IndexError: list index out of range ``` These look very similar to the #63077 but not quite the same and in a different module. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lineinfile ##### ANSIBLE VERSION ``` testu18@testu18:~$ ansible --version ansible 2.8.6 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/testu18/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ``` testu18@testu18:~$ ansible-config dump --only-changed testu18@testu18:~$ ``` ##### OS / ENVIRONMENT Ubuntu 18.04 and Mac os 10.14.6 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: localhost tasks: - lineinfile: path: "/tmp/somefile" line: "[easy_install]" create: yes - lineinfile: path: "/tmp/somefile" insertafter: "\\[easy_install\\]" regexp: "^\\s*index-url\\s+=.*$" line: "index-url = https://example.org" ``` ##### EXPECTED RESULTS ``` IT-USA-25903:test csalch$ ansible-playbook test_playbook.yml [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************* TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************************************************************************************************************************************** ok: [localhost] TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** changed: [localhost] TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** changed: [localhost] PLAY RECAP *************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** localhost : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` testu18@testu18:~$ ansible-playbook ./test_playbook.yml -vvvv ansible-playbook 2.8.6 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/testu18/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible-playbook python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] Using /etc/ansible/ansible.cfg as config file setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Parsed /etc/ansible/hosts inventory source with ini plugin [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test_playbook.yml ********************************************************************************************************************************************************************************************************************************************************************************************************************************************** Positional arguments: ./test_playbook.yml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) verbosity: 4 connection: smart timeout: 10 1 plays in ./test_playbook.yml PLAY [localhost] ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************* TASK [Gathering Facts] *************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:2 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789 `" && echo ansible-tmp-1571406272.54-212983197612789="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/system/setup.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmpkcGtMZ TO /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/ /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406272.54-212983197612789/ > /dev/null 2>&1 && sleep 0' ok: [localhost] META: ran handlers TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:4 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449 `" && echo ansible-tmp-1571406273.37-22574126030449="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/files/lineinfile.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmp_GotGN TO /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/ /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406273.37-22574126030449/ > /dev/null 2>&1 && sleep 0' ok: [localhost] => { "backup": "", "changed": false, "diff": [ { "after": "", "after_header": "/tmp/somefile (content)", "before": "", "before_header": "/tmp/somefile (content)" }, { "after_header": "/tmp/somefile (file attributes)", "before_header": "/tmp/somefile (file attributes)" } ], "invocation": { "module_args": { "attributes": null, "backrefs": false, "backup": false, "content": null, "create": true, "delimiter": null, "directory_mode": null, "firstmatch": false, "follow": false, "force": null, "group": null, "insertafter": null, "insertbefore": null, "line": "[easy_install]", "mode": null, "owner": null, "path": "/tmp/somefile", "regexp": null, "remote_src": null, "selevel": null, "serole": null, "setype": null, "seuser": null, "src": null, "state": "present", "unsafe_writes": null, "validate": null } }, "msg": "" } TASK [lineinfile] ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************** task path: /home/testu18/test_playbook.yml:9 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: testu18 <127.0.0.1> EXEC /bin/sh -c 'echo ~testu18 && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258 `" && echo ansible-tmp-1571406273.68-75225899370258="` echo /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258 `" ) && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/files/lineinfile.py <127.0.0.1> PUT /home/testu18/.ansible/tmp/ansible-local-11042z9TmO6/tmp34bPPv TO /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/ /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 114, in <module> _ansiballz_main() File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py", line 49, in invoke_module imp.load_module('__main__', mod, module, MOD_DESC) File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 567, in <module> File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 558, in main File "/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py", line 413, in present IndexError: list index out of range fatal: [localhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 114, in <module>\n _ansiballz_main()\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/testu18/.ansible/tmp/ansible-tmp-1571406273.68-75225899370258/AnsiballZ_lineinfile.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 567, in <module>\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 558, in main\n File \"/tmp/ansible_lineinfile_payload_BHn2mK/__main__.py\", line 413, in present\nIndexError: list index out of range\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } PLAY RECAP *************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** localhost ```
https://github.com/ansible/ansible/issues/63684
https://github.com/ansible/ansible/pull/63696
05c8e33983802cf2f3dd6af6fb2da8a94bc6914d
92cd13a2cff295c7cd5f196c3e30b9db4c9f1c1a
2019-10-18T13:45:17Z
python
2019-10-22T14:39:58Z
test/integration/targets/lineinfile/tasks/main.yml
# test code for the lineinfile module # (c) 2014, James Cammarata <[email protected]> # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. - name: deploy the test file for lineinfile copy: src: test.txt dest: "{{ output_dir }}/test.txt" register: result - name: assert that the test file was deployed assert: that: - result is changed - "result.checksum == '5feac65e442c91f557fc90069ce6efc4d346ab51'" - "result.state == 'file'" - name: insert a line at the beginning of the file, and back it up lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line at the beginning" insertbefore: "BOF" backup: yes register: result1 - name: insert a line at the beginning of the file again lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line at the beginning" insertbefore: "BOF" register: result2 - name: assert that the line was inserted at the head of the file assert: that: - result1 is changed - result2 is not changed - result1.msg == 'line added' - result1.backup != '' - name: stat the backup file stat: path: "{{ result1.backup }}" register: result - name: assert the backup file matches the previous hash assert: that: - "result.stat.checksum == '5feac65e442c91f557fc90069ce6efc4d346ab51'" - name: stat the test after the insert at the head stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test hash is what we expect for the file with the insert at the head assert: that: - "result.stat.checksum == '7eade4042b23b800958fe807b5bfc29f8541ec09'" - name: insert a line at the end of the file lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line at the end" insertafter: "EOF" register: result - name: assert that the line was inserted at the end of the file assert: that: - result is changed - "result.msg == 'line added'" - name: stat the test after the insert at the end stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the insert at the end assert: that: - "result.stat.checksum == 'fb57af7dc10a1006061b000f1f04c38e4bef50a9'" - name: insert a line after the first line lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line after line 1" insertafter: "^This is line 1$" register: result - name: assert that the line was inserted after the first line assert: that: - result is changed - "result.msg == 'line added'" - name: stat the test after insert after the first line stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the insert after the first line assert: that: - "result.stat.checksum == '5348da605b1bc93dbadf3a16474cdf22ef975bec'" - name: insert a line before the last line lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New line before line 5" insertbefore: "^This is line 5$" register: result - name: assert that the line was inserted before the last line assert: that: - result is changed - "result.msg == 'line added'" - name: stat the test after the insert before the last line stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the insert before the last line assert: that: - "result.stat.checksum == '2e9e460ff68929e4453eb765761fd99814f6e286'" - name: Replace a line with backrefs lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "This is line 3" backrefs: yes regexp: "^(REF) .* \\1$" register: backrefs_result1 - name: Replace a line with backrefs again lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "This is line 3" backrefs: yes regexp: "^(REF) .* \\1$" register: backrefs_result2 - command: cat {{ output_dir }}/test.txt - name: assert that the line with backrefs was changed assert: that: - backrefs_result1 is changed - backrefs_result2 is not changed - "backrefs_result1.msg == 'line replaced'" - name: stat the test after the backref line was replaced stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '72f60239a735ae06e769d823f5c2b4232c634d9c'" - name: remove the middle line lineinfile: dest: "{{ output_dir }}/test.txt" state: absent regexp: "^This is line 3$" register: result - name: assert that the line was removed assert: that: - result is changed - "result.msg == '1 line(s) removed'" - name: stat the test after the middle line was removed stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the middle line was removed assert: that: - "result.stat.checksum == 'd4eeb07bdebab2d1cdb3ec4a3635afa2618ad4ea'" - name: run a validation script that succeeds lineinfile: dest: "{{ output_dir }}/test.txt" state: absent regexp: "^This is line 5$" validate: "true %s" register: result - name: assert that the file validated after removing a line assert: that: - result is changed - "result.msg == '1 line(s) removed'" - name: stat the test after the validation succeeded stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after the validation succeeded assert: that: - "result.stat.checksum == 'ab56c210ea82839a54487464800fed4878cb2608'" - name: run a validation script that fails lineinfile: dest: "{{ output_dir }}/test.txt" state: absent regexp: "^This is line 1$" validate: "/bin/false %s" register: result ignore_errors: yes - name: assert that the validate failed assert: that: - "result.failed == true" - name: stat the test after the validation failed stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches the previous after the validation failed assert: that: - "result.stat.checksum == 'ab56c210ea82839a54487464800fed4878cb2608'" - name: use create=yes lineinfile: dest: "{{ output_dir }}/new_test.txt" create: yes insertbefore: BOF state: present line: "This is a new file" register: result - name: assert that the new file was created assert: that: - result is changed - "result.msg == 'line added'" - name: validate that the newly created file exists stat: path: "{{ output_dir }}/new_test.txt" register: result ignore_errors: yes - name: assert the newly created test checksum matches assert: that: - "result.stat.checksum == '038f10f9e31202451b093163e81e06fbac0c6f3a'" # Test EOF in cases where file has no newline at EOF - name: testnoeof deploy the file for lineinfile copy: src: testnoeof.txt dest: "{{ output_dir }}/testnoeof.txt" register: result - name: testnoeof insert a line at the end of the file lineinfile: dest: "{{ output_dir }}/testnoeof.txt" state: present line: "New line at the end" insertafter: "EOF" register: result - name: testempty assert that the line was inserted at the end of the file assert: that: - result is changed - "result.msg == 'line added'" - name: insert a multiple lines at the end of the file lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "This is a line\nwith \\n character" insertafter: "EOF" register: result - name: assert that the multiple lines was inserted assert: that: - result is changed - "result.msg == 'line added'" - name: testnoeof stat the no newline EOF test after the insert at the end stat: path: "{{ output_dir }}/testnoeof.txt" register: result - name: testnoeof assert test checksum matches after the insert at the end assert: that: - "result.stat.checksum == 'f9af7008e3cb67575ce653d094c79cabebf6e523'" # Test EOF with empty file to make sure no unnecessary newline is added - name: testempty deploy the testempty file for lineinfile copy: src: testempty.txt dest: "{{ output_dir }}/testempty.txt" register: result - name: testempty insert a line at the end of the file lineinfile: dest: "{{ output_dir }}/testempty.txt" state: present line: "New line at the end" insertafter: "EOF" register: result - name: testempty assert that the line was inserted at the end of the file assert: that: - result is changed - "result.msg == 'line added'" - name: testempty stat the test after the insert at the end stat: path: "{{ output_dir }}/testempty.txt" register: result - name: testempty assert test checksum matches after the insert at the end assert: that: - "result.stat.checksum == 'f440dc65ea9cec3fd496c1479ddf937e1b949412'" - stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after inserting multiple lines assert: that: - "result.stat.checksum == 'fde683229429a4f05d670e6c10afc875e1d5c489'" - name: replace a line with backrefs included in the line lineinfile: dest: "{{ output_dir }}/test.txt" state: present line: "New \\1 created with the backref" backrefs: yes regexp: "^This is (line 4)$" register: result - name: assert that the line with backrefs was changed assert: that: - result is changed - "result.msg == 'line replaced'" - name: stat the test after the backref line was replaced stat: path: "{{ output_dir }}/test.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '981ad35c4b30b03bc3a1beedce0d1e72c491898e'" ################################################################### # issue 8535 - name: create a new file for testing quoting issues file: dest: "{{ output_dir }}/test_quoting.txt" state: touch register: result - name: assert the new file was created assert: that: - result is changed - name: use with_items to add code-like strings to the quoting txt file lineinfile: dest: "{{ output_dir }}/test_quoting.txt" line: "{{ item }}" insertbefore: BOF with_items: - "'foo'" - "dotenv.load();" - "var dotenv = require('dotenv');" register: result - name: assert the quote test file was modified correctly assert: that: - result.results|length == 3 - result.results[0] is changed - result.results[0].item == "'foo'" - result.results[1] is changed - result.results[1].item == "dotenv.load();" - result.results[2] is changed - result.results[2].item == "var dotenv = require('dotenv');" - name: stat the quote test file stat: path: "{{ output_dir }}/test_quoting.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '7dc3cb033c3971e73af0eaed6623d4e71e5743f1'" - name: insert a line into the quoted file with a single quote lineinfile: dest: "{{ output_dir }}/test_quoting.txt" line: "import g'" register: result - name: assert that the quoted file was changed assert: that: - result is changed - name: stat the quote test file stat: path: "{{ output_dir }}/test_quoting.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == '73b271c2cc1cef5663713bc0f00444b4bf9f4543'" - name: insert a line into the quoted file with many double quotation strings lineinfile: dest: "{{ output_dir }}/test_quoting.txt" line: "\"quote\" and \"unquote\"" register: result - name: assert that the quoted file was changed assert: that: - result is changed - name: stat the quote test file stat: path: "{{ output_dir }}/test_quoting.txt" register: result - name: assert test checksum matches after backref line was replaced assert: that: - "result.stat.checksum == 'b10ab2a3c3b6492680c8d0b1d6f35aa6b8f9e731'" ################################################################### # Issue 28721 - name: Deploy the testmultiple file copy: src: testmultiple.txt dest: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the testmultiple file was deployed assert: that: - result is changed - result.checksum == '3e0090a34fb641f3c01e9011546ff586260ea0ea' - result.state == 'file' # Test insertafter - name: Write the same line to a file inserted after different lines lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertafter: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_1 with_items: "{{ test_regexp }}" - name: Assert that the line is added once only assert: that: - _multitest_1.results.0 is changed - _multitest_1.results.1 is not changed - _multitest_1.results.2 is not changed - _multitest_1.results.3 is not changed - name: Do the same thing again to check for changes lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertafter: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_2 with_items: "{{ test_regexp }}" - name: Assert that the line is not added anymore assert: that: - _multitest_2.results.0 is not changed - _multitest_2.results.1 is not changed - _multitest_2.results.2 is not changed - _multitest_2.results.3 is not changed - name: Stat the insertafter file stat: path: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the insertafter file matches expected checksum assert: that: - result.stat.checksum == 'c6733b6c53ddd0e11e6ba39daa556ef8f4840761' # Test insertbefore - name: Deploy the testmultiple file copy: src: testmultiple.txt dest: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the testmultiple file was deployed assert: that: - result is changed - result.checksum == '3e0090a34fb641f3c01e9011546ff586260ea0ea' - result.state == 'file' - name: Write the same line to a file inserted before different lines lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertbefore: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_3 with_items: "{{ test_regexp }}" - name: Assert that the line is added once only assert: that: - _multitest_3.results.0 is changed - _multitest_3.results.1 is not changed - _multitest_3.results.2 is not changed - _multitest_3.results.3 is not changed - name: Do the same thing again to check for changes lineinfile: path: "{{ output_dir }}/testmultiple.txt" insertbefore: "{{ item.regex }}" line: "{{ item.replace }}" register: _multitest_4 with_items: "{{ test_regexp }}" - name: Assert that the line is not added anymore assert: that: - _multitest_4.results.0 is not changed - _multitest_4.results.1 is not changed - _multitest_4.results.2 is not changed - _multitest_4.results.3 is not changed - name: Stat the insertbefore file stat: path: "{{ output_dir }}/testmultiple.txt" register: result - name: Assert that the insertbefore file matches expected checksum assert: that: - result.stat.checksum == '5d298651fbc377b45257da10308a9dc2fe1f8be5' ################################################################### # Issue 36156 # Test insertbefore and insertafter with regexp - name: Deploy the test.conf file copy: src: test.conf dest: "{{ output_dir }}/test.conf" register: result - name: Assert that the test.conf file was deployed assert: that: - result is changed - result.checksum == '6037f13e419b132eb3fd20a89e60c6c87a6add38' - result.state == 'file' # Test instertafter - name: Insert lines after with regexp lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertafter: "{{ item.after }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_5 - name: Do the same thing again and check for changes lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertafter: "{{ item.after }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_6 - name: Assert that the file was changed the first time but not the second time assert: that: - item.0 is changed - item.1 is not changed with_together: - "{{ _multitest_5.results }}" - "{{ _multitest_6.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == '06e2c456e5028dd7bcd0b117b5927a1139458c82' - name: Do the same thing a third time without regexp and check for changes lineinfile: path: "{{ output_dir }}/test.conf" line: "{{ item.line }}" insertafter: "{{ item.after }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_7 - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file was changed when no regexp was provided assert: that: - item is not changed with_items: "{{ _multitest_7.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == '06e2c456e5028dd7bcd0b117b5927a1139458c82' # Test insertbefore - name: Deploy the test.conf file copy: src: test.conf dest: "{{ output_dir }}/test.conf" register: result - name: Assert that the test.conf file was deployed assert: that: - result is changed - result.checksum == '6037f13e419b132eb3fd20a89e60c6c87a6add38' - result.state == 'file' - name: Insert lines before with regexp lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertbefore: "{{ item.before }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_8 - name: Do the same thing again and check for changes lineinfile: path: "{{ output_dir }}/test.conf" regexp: "{{ item.regexp }}" line: "{{ item.line }}" insertbefore: "{{ item.before }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_9 - name: Assert that the file was changed the first time but not the second time assert: that: - item.0 is changed - item.1 is not changed with_together: - "{{ _multitest_8.results }}" - "{{ _multitest_9.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == 'c3be9438a07c44d4c256cebfcdbca15a15b1db91' - name: Do the same thing a third time without regexp and check for changes lineinfile: path: "{{ output_dir }}/test.conf" line: "{{ item.line }}" insertbefore: "{{ item.before }}" with_items: "{{ test_befaf_regexp }}" register: _multitest_10 - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file was changed when no regexp was provided assert: that: - item is not changed with_items: "{{ _multitest_10.results }}" - name: Stat the file stat: path: "{{ output_dir }}/test.conf" register: result - name: Assert that the file contents match what is expected assert: that: - result.stat.checksum == 'c3be9438a07c44d4c256cebfcdbca15a15b1db91' - name: Copy empty file to test with insertbefore copy: src: testempty.txt dest: "{{ output_dir }}/testempty.txt" - name: Add a line to empty file with insertbefore lineinfile: path: "{{ output_dir }}/testempty.txt" line: top insertbefore: '^not in the file$' register: oneline_insbefore_test1 - name: Add a line to file with only one line using insertbefore lineinfile: path: "{{ output_dir }}/testempty.txt" line: top insertbefore: '^not in the file$' register: oneline_insbefore_test2 - name: Stat the file stat: path: "{{ output_dir }}/testempty.txt" register: oneline_insbefore_file - name: Assert that insertebefore worked properly with a one line file assert: that: - oneline_insbefore_test1 is changed - oneline_insbefore_test2 is not changed - oneline_insbefore_file.stat.checksum == '4dca56d05a21f0d018cd311f43e134e4501cf6d9' ################################################################### # Issue 29443 # When using an empty regexp, replace the last line (since it matches every line) # but also provide a warning. - name: Deploy the test file for lineinfile copy: src: test.txt dest: "{{ output_dir }}/test.txt" register: result - name: Assert that the test file was deployed assert: that: - result is changed - result.checksum == '5feac65e442c91f557fc90069ce6efc4d346ab51' - result.state == 'file' - name: Insert a line in the file using an empty string as a regular expression lineinfile: path: "{{ output_dir }}/test.txt" regexp: '' line: This is line 6 register: insert_empty_regexp - name: Stat the file stat: path: "{{ output_dir }}/test.txt" register: result - name: Assert that the file contents match what is expected and a warning was displayed assert: that: - insert_empty_regexp is changed - warning_message in insert_empty_regexp.warnings - result.stat.checksum == '23555a98ceaa88756b4c7c7bba49d9f86eed868f' vars: warning_message: >- The regular expression is an empty string, which will match every line in the file. This may have unintended consequences, such as replacing the last line in the file rather than appending. If this is desired, use '^' to match every line in the file and avoid this warning. ################################################################### ## Issue #58923 ## Using firstmatch with insertafter and ensure multiple lines are not inserted - name: Deploy the firstmatch test file copy: src: firstmatch.txt dest: "{{ output_dir }}/firstmatch.txt" register: result - name: Assert that the test file was deployed assert: that: - result is changed - result.checksum == '1d644e5e2e51c67f1bd12d7bbe2686017f39923d' - result.state == 'file' - name: Insert a line before an existing line using firstmatch lineinfile: path: "{{ output_dir }}/firstmatch.txt" line: INSERT insertafter: line1 firstmatch: yes register: insertafter1 - name: Insert a line before an existing line using firstmatch again lineinfile: path: "{{ output_dir }}/firstmatch.txt" line: INSERT insertafter: line1 firstmatch: yes register: insertafter2 - name: Stat the file stat: path: "{{ output_dir }}/firstmatch.txt" register: result - name: Assert that the file was modified appropriately assert: that: - insertafter1 is changed - insertafter2 is not changed - result.stat.checksum == '114aae024073a3ee8ec8db0ada03c5483326dd86' ######################################################################################## # Tests of fixing the same issue as above (#58923) by @Andersson007 <[email protected]> # and @samdoran <[email protected]>: # Test insertafter with regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' # Regarding the documentation: # If regular expressions are passed to both regexp and # insertafter, insertafter is only honored if no match for regexp is found. # Therefore, # when regular expressions are passed to both regexp and insertafter, then: # 1. regexp was found -> ignore insertafter, replace the founded line # 2. regexp was not found -> insert the line after 'insertafter' line # Regexp is not present in the file, so the line must be inserted after ^#!/bin/sh - name: Add the line using firstmatch, regexp, and insertafter lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test1 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test1_file - name: Add the line using firstmatch, regexp, and insertafter again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test2 # Check of the prev step. # We tried to add the same line with the same playbook, # so nothing has been added: - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test2_file - name: Assert insertafter tests gave the expected results assert: that: - insertafter_test1 is changed - insertafter_test1_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' - insertafter_test2 is not changed - insertafter_test2_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' # Test insertafter without regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' - name: Insert the line using firstmatch and insertafter without regexp lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test3 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test3_file - name: Insert the line using firstmatch and insertafter without regexp again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertafter: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertafter_test4 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertafter_test4_file - name: Assert insertafter without regexp tests gave the expected results assert: that: - insertafter_test3 is changed - insertafter_test3_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' - insertafter_test4 is not changed - insertafter_test4_file.stat.checksum == '9232aed6fe88714964d9e29d13e42cd782070b08' # Test insertbefore with regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' - name: Add the line using regexp, firstmatch, and insertbefore lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test1 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test1_file - name: Add the line using regexp, firstmatch, and insertbefore again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' regexp: ^export FISHEYE_OPTS firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test2 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test2_file - name: Assert insertbefore with regexp tests gave the expected results assert: that: - insertbefore_test1 is changed - insertbefore_test1_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' - insertbefore_test2 is not changed - insertbefore_test2_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' # Test insertbefore without regexp - name: Deploy the test file copy: src: test_58923.txt dest: "{{ output_dir }}/test_58923.txt" register: initial_file - name: Assert that the test file was deployed assert: that: - initial_file is changed - initial_file.checksum == 'b6379ba43261c451a62102acb2c7f438a177c66e' - initial_file.state == 'file' - name: Add the line using insertbefore and firstmatch lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test3 - name: Stat the file stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test3_file - name: Add the line using insertbefore and firstmatch again lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: '^#!/bin/sh' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test4 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test4_file # Test when the line is presented in the file but # not in the before/after spot and it does match the regexp: - name: > Add the line using insertbefore and firstmatch when the regexp line is presented but not close to insertbefore spot lineinfile: path: "{{ output_dir }}/test_58923.txt" insertbefore: ' Darwin\*\) if \[ -z \"\$JAVA_HOME\" \] ; then' firstmatch: true line: export FISHEYE_OPTS="-Xmx4096m -Xms2048m" register: insertbefore_test5 - name: Stat the file again stat: path: "{{ output_dir }}/test_58923.txt" register: insertbefore_test5_file - name: Assert insertbefore with regexp tests gave the expected results assert: that: - insertbefore_test3 is changed - insertbefore_test3_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' - insertbefore_test4 is not changed - insertbefore_test4_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7' - insertbefore_test5 is not changed - insertbefore_test5_file.stat.checksum == '3c6630b9d44f561ea9ad999be56a7504cadc12f7'
closed
ansible/ansible
https://github.com/ansible/ansible
62,723
Import sanity test not checking module main function
##### SUMMARY When checking Ansible modules, the import sanity test should check modules twice, once with `__name__` set to `'__main__'` and once without, so that modules can be checked up to the point that `AnsibleModule` is instantiated. This works correctly for Ansible 2.8 and earlier, but in Ansible 2.9 the checking with `__name__` set to `'__main__'` no longer occurs. ##### ISSUE TYPE Bug Report ##### COMPONENT NAME ansible-test ##### ANSIBLE VERSION 2.9.0rc1 ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE ``` ansible-test coverage erase ansible-test sanity --test import ping --docker -v --coverage --python 3.7 ansible-test coverage html ``` Look at the coverage results for the `ping` module and notice that under Ansible 2.8 and earlier the `__name__ == '__main__'` branch is covered, but under Ansible 2.9 it is not. ##### EXPECTED RESULTS Ansible modules are checked with `__name__` set to `'__main__'` and not. ##### ACTUAL RESULTS Ansible modules are checked only with `__name__` not set to `'__main__'`.
https://github.com/ansible/ansible/issues/62723
https://github.com/ansible/ansible/pull/63830
b52d7155678017340fd39711b335ec2c582d6783
92ccdeac31902803c953792d9af929c7edf93f60
2019-09-22T17:08:20Z
python
2019-10-23T06:00:35Z
test/lib/ansible_test/_data/sanity/import/importer.py
#!/usr/bin/env python """Import the given python module(s) and report error(s) encountered.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type def main(): """ Main program function used to isolate globals from imported code. Changes to globals in imported modules on Python 2.7 will overwrite our own globals. """ import contextlib import os import re import sys import traceback import warnings import_dir = os.environ['SANITY_IMPORT_DIR'] minimal_dir = os.environ['SANITY_MINIMAL_DIR'] try: import importlib.util imp = None # pylint: disable=invalid-name except ImportError: importlib = None # pylint: disable=invalid-name import imp try: # noinspection PyCompatibility from StringIO import StringIO except ImportError: from io import StringIO import ansible.module_utils.basic import ansible.module_utils.common.removed try: from ansible.utils.collection_loader import AnsibleCollectionLoader except ImportError: # noinspection PyPep8Naming AnsibleCollectionLoader = None # These are the public attribute sof a doc-only module doc_keys = ('ANSIBLE_METADATA', 'DOCUMENTATION', 'EXAMPLES', 'RETURN', 'absolute_import', 'division', 'print_function') class ImporterAnsibleModuleException(Exception): """Exception thrown during initialization of ImporterAnsibleModule.""" class ImporterAnsibleModule: """Replacement for AnsibleModule to support import testing.""" def __init__(self, *args, **kwargs): raise ImporterAnsibleModuleException() # stop Ansible module execution during AnsibleModule instantiation ansible.module_utils.basic.AnsibleModule = ImporterAnsibleModule # no-op for _load_params since it may be called before instantiating AnsibleModule ansible.module_utils.basic._load_params = lambda *args, **kwargs: {} # pylint: disable=protected-access # no-op for removed_module since it is called in place of AnsibleModule instantiation ansible.module_utils.common.removed.removed_module = lambda *args, **kwargs: None def run(): """Main program function.""" base_dir = os.getcwd() messages = set() if AnsibleCollectionLoader: # allow importing code from collections # noinspection PyCallingNonCallable sys.meta_path.insert(0, AnsibleCollectionLoader()) for path in sys.argv[1:] or sys.stdin.read().splitlines(): test_python_module(path, base_dir, messages, False) test_python_module(path, base_dir, messages, True) if messages: exit(10) def test_python_module(path, base_dir, messages, ansible_module): if ansible_module: # importing modules with __main__ under Python 2.6 exits with status code 1 if sys.version_info < (2, 7): return # only run __main__ protected code for Ansible modules if not path.startswith('lib/ansible/modules/'): return # __init__ in module directories is empty (enforced by a different test) if path.endswith('__init__.py'): return # async_wrapper is not an Ansible module if path == 'lib/ansible/modules/utilities/logic/async_wrapper.py': return name = calculate_python_module_name(path) # show the Ansible module responsible for the exception, even if it was thrown in module_utils filter_dir = os.path.join(base_dir, 'lib/ansible/modules') else: # Calculate module name name = calculate_python_module_name(path) # show the Ansible file responsible for the exception, even if it was thrown in 3rd party code filter_dir = base_dir capture = Capture() try: if imp: with capture_output(capture): # On Python2 without absolute_import we have to import parent modules all # the way up the tree full_path = os.path.abspath(path) parent_mod = None py_packages = name.split('.') # BIG HACK: reimporting module_utils breaks the monkeypatching of basic we did # above and also breaks modules which import names directly from module_utils # modules (you'll get errors like ERROR: # lib/ansible/modules/storage/netapp/na_ontap_vserver_cifs_security.py:151:0: # AttributeError: 'module' object has no attribute 'netapp'). # So when we import a module_util here, use a munged name. if 'module_utils' in py_packages: # Avoid accidental double underscores by using _1 as a prefix py_packages[-1] = '_1%s' % py_packages[-1] name = '.'.join(py_packages) for idx in range(1, len(py_packages)): parent_name = '.'.join(py_packages[:idx]) if parent_mod is None: toplevel_end = full_path.find('ansible/module') toplevel = full_path[:toplevel_end] parent_mod_info = imp.find_module(parent_name, [toplevel]) else: parent_mod_info = imp.find_module(py_packages[idx - 1], parent_mod.__path__) parent_mod = imp.load_module(parent_name, *parent_mod_info) # skip distro due to an apparent bug or bad interaction in # imp.load_module() with our distro/__init__.py. # distro/__init__.py sets sys.modules['ansible.module_utils.distro'] # = _distro.pyc # but after running imp.load_module(), # sys.modules['ansible.module_utils.distro._distro'] = __init__.pyc # (The opposite of what we set) # This does not affect runtime so regular import seems to work. It's # just imp.load_module() if name == 'ansible.module_utils.distro._1__init__': return with open(path, 'r') as module_fd: module = imp.load_module(name, module_fd, full_path, ('.py', 'r', imp.PY_SOURCE)) if ansible_module: run_if_really_module(module) else: spec = importlib.util.spec_from_file_location(name, os.path.abspath(path)) module = importlib.util.module_from_spec(spec) with capture_output(capture): spec.loader.exec_module(module) if ansible_module: run_if_really_module(module) capture_report(path, capture, messages) except ImporterAnsibleModuleException: # module instantiated AnsibleModule without raising an exception pass # We truly want to catch anything the plugin might do here, including call sys.exit() so we # catch BaseException except BaseException as ex: # pylint: disable=locally-disabled, broad-except capture_report(path, capture, messages) exc_type, _exc, exc_tb = sys.exc_info() message = str(ex) results = list(reversed(traceback.extract_tb(exc_tb))) source = None line = 0 offset = 0 if isinstance(ex, SyntaxError) and ex.filename.endswith(path): # pylint: disable=locally-disabled, no-member # A SyntaxError in the source we're importing will have the correct path, line and offset. # However, the traceback will report the path to this importer.py script instead. # We'll use the details from the SyntaxError in this case, as it's more accurate. source = path line = ex.lineno or 0 # pylint: disable=locally-disabled, no-member offset = ex.offset or 0 # pylint: disable=locally-disabled, no-member message = str(ex) # Hack to remove the filename and line number from the message, if present. message = message.replace(' (%s, line %d)' % (os.path.basename(path), line), '') else: for result in results: if result[0].startswith(filter_dir): source = result[0][len(base_dir) + 1:].replace('test/lib/ansible_test/_data/sanity/import/', '') line = result[1] or 0 break if not source: # If none of our source files are found in the traceback, report the file we were testing. # I haven't been able to come up with a test case that encounters this issue yet. source = path message += ' (in %s:%d)' % (results[-1][0], results[-1][1] or 0) message = re.sub(r'\n *', ': ', message) error = '%s:%d:%d: %s: %s' % (source, line, offset, exc_type.__name__, message) report_message(error, messages) def run_if_really_module(module): # Module was removed if ('removed' not in module.ANSIBLE_METADATA['status'] and # Documentation only module [attr for attr in (frozenset(module.__dict__.keys()).difference(doc_keys)) if not (attr.startswith('__') and attr.endswith('__'))]): # Run main() code for ansible_modules module.main() def calculate_python_module_name(path): name = None try: idx = path.index('ansible/modules') except ValueError: try: idx = path.index('ansible/module_utils') except ValueError: try: idx = path.index('ansible_collections') except ValueError: # Default name = 'module_import_test' if name is None: name = path[idx:-len('.py')].replace('/', '.') return name class Capture: """Captured output and/or exception.""" def __init__(self): self.stdout = StringIO() self.stderr = StringIO() self.warnings = [] def capture_report(path, capture, messages): """Report on captured output. :type path: str :type capture: Capture :type messages: set[str] """ if capture.stdout.getvalue(): first = capture.stdout.getvalue().strip().splitlines()[0].strip() message = '%s:%d:%d: %s: %s' % (path, 0, 0, 'StandardOutputUsed', first) report_message(message, messages) if capture.stderr.getvalue(): first = capture.stderr.getvalue().strip().splitlines()[0].strip() message = '%s:%d:%d: %s: %s' % (path, 0, 0, 'StandardErrorUsed', first) report_message(message, messages) for warning in capture.warnings: msg = re.sub(r'\s+', ' ', '%s' % warning.message).strip() filepath = os.path.relpath(warning.filename) lineno = warning.lineno if filepath.startswith('../') or filepath.startswith(minimal_dir): # The warning occurred outside our source tree. # The best we can do is to report the file which was tested that triggered the warning. # If the responsible import is in shared code this warning will be repeated for each file tested which imports the shared code. msg += ' (in %s:%d)' % (warning.filename, warning.lineno) filepath = path lineno = 0 elif filepath.startswith(import_dir): # Strip the import dir from warning paths in shared code. # Needed when warnings occur in places like module_utils but are caught by the modules importing the module_utils. filepath = os.path.relpath(filepath, import_dir) message = '%s:%d:%d: %s: %s' % (filepath, lineno, 0, warning.category.__name__, msg) report_message(message, messages) def report_message(message, messages): """Report message if not already reported. :type message: str :type messages: set[str] """ if message not in messages: messages.add(message) print(message) @contextlib.contextmanager def capture_output(capture): """Capture sys.stdout and sys.stderr. :type capture: Capture """ old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = capture.stdout sys.stderr = capture.stderr with warnings.catch_warnings(record=True) as captured_warnings: try: yield finally: capture.warnings = captured_warnings sys.stdout = old_stdout sys.stderr = old_stderr run() if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
62,723
Import sanity test not checking module main function
##### SUMMARY When checking Ansible modules, the import sanity test should check modules twice, once with `__name__` set to `'__main__'` and once without, so that modules can be checked up to the point that `AnsibleModule` is instantiated. This works correctly for Ansible 2.8 and earlier, but in Ansible 2.9 the checking with `__name__` set to `'__main__'` no longer occurs. ##### ISSUE TYPE Bug Report ##### COMPONENT NAME ansible-test ##### ANSIBLE VERSION 2.9.0rc1 ##### CONFIGURATION N/A ##### OS / ENVIRONMENT N/A ##### STEPS TO REPRODUCE ``` ansible-test coverage erase ansible-test sanity --test import ping --docker -v --coverage --python 3.7 ansible-test coverage html ``` Look at the coverage results for the `ping` module and notice that under Ansible 2.8 and earlier the `__name__ == '__main__'` branch is covered, but under Ansible 2.9 it is not. ##### EXPECTED RESULTS Ansible modules are checked with `__name__` set to `'__main__'` and not. ##### ACTUAL RESULTS Ansible modules are checked only with `__name__` not set to `'__main__'`.
https://github.com/ansible/ansible/issues/62723
https://github.com/ansible/ansible/pull/63830
b52d7155678017340fd39711b335ec2c582d6783
92ccdeac31902803c953792d9af929c7edf93f60
2019-09-22T17:08:20Z
python
2019-10-23T06:00:35Z
test/lib/ansible_test/_internal/sanity/import.py
"""Sanity test for proper import exception handling.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from .. import types as t from ..sanity import ( SanityMultipleVersion, SanityMessage, SanityFailure, SanitySuccess, SanitySkipped, SANITY_ROOT, ) from ..target import ( TestTarget, ) from ..util import ( SubprocessError, remove_tree, display, parse_to_list_of_dict, is_subdir, ANSIBLE_LIB_ROOT, generate_pip_command, find_python, ) from ..util_common import ( intercept_command, run_command, write_text_file, ResultType, ) from ..ansible_util import ( ansible_environment, ) from ..executor import ( generate_pip_install, ) from ..config import ( SanityConfig, ) from ..coverage_util import ( coverage_context, ) from ..venv import ( create_virtual_environment, ) from ..data import ( data_context, ) class ImportTest(SanityMultipleVersion): """Sanity test for proper import exception handling.""" def filter_targets(self, targets): # type: (t.List[TestTarget]) -> t.List[TestTarget] """Return the given list of test targets, filtered to include only those relevant for the test.""" return [target for target in targets if os.path.splitext(target.path)[1] == '.py' and (is_subdir(target.path, data_context().content.module_path) or is_subdir(target.path, data_context().content.module_utils_path))] def test(self, args, targets, python_version): """ :type args: SanityConfig :type targets: SanityTargets :type python_version: str :rtype: TestResult """ capture_pip = args.verbosity < 2 if python_version.startswith('2.') and args.requirements: # hack to make sure that virtualenv is available under Python 2.x # on Python 3.x we can use the built-in venv pip = generate_pip_command(find_python(python_version)) run_command(args, generate_pip_install(pip, 'sanity.import', packages=['virtualenv']), capture=capture_pip) settings = self.load_processor(args, python_version) paths = [target.path for target in targets.include] env = ansible_environment(args, color=False) temp_root = os.path.join(ResultType.TMP.path, 'sanity', 'import') # create a clean virtual environment to minimize the available imports beyond the python standard library virtual_environment_path = os.path.join(temp_root, 'minimal-py%s' % python_version.replace('.', '')) virtual_environment_bin = os.path.join(virtual_environment_path, 'bin') remove_tree(virtual_environment_path) if not create_virtual_environment(args, python_version, virtual_environment_path): display.warning("Skipping sanity test '%s' on Python %s due to missing virtual environment support." % (self.name, python_version)) return SanitySkipped(self.name, python_version) # add the importer to our virtual environment so it can be accessed through the coverage injector importer_path = os.path.join(virtual_environment_bin, 'importer.py') if not args.explain: os.symlink(os.path.abspath(os.path.join(SANITY_ROOT, 'import', 'importer.py')), importer_path) # create a minimal python library python_path = os.path.join(temp_root, 'lib') ansible_path = os.path.join(python_path, 'ansible') ansible_init = os.path.join(ansible_path, '__init__.py') ansible_link = os.path.join(ansible_path, 'module_utils') if not args.explain: remove_tree(ansible_path) write_text_file(ansible_init, '', create_directories=True) os.symlink(os.path.join(ANSIBLE_LIB_ROOT, 'module_utils'), ansible_link) if data_context().content.collection: # inject just enough Ansible code for the collections loader to work on all supported Python versions # the __init__.py files are needed only for Python 2.x # the empty modules directory is required for the collection loader to generate the synthetic packages list write_text_file(os.path.join(ansible_path, 'utils/__init__.py'), '', create_directories=True) os.symlink(os.path.join(ANSIBLE_LIB_ROOT, 'utils', 'collection_loader.py'), os.path.join(ansible_path, 'utils', 'collection_loader.py')) os.symlink(os.path.join(ANSIBLE_LIB_ROOT, 'utils', 'singleton.py'), os.path.join(ansible_path, 'utils', 'singleton.py')) write_text_file(os.path.join(ansible_path, 'modules/__init__.py'), '', create_directories=True) # activate the virtual environment env['PATH'] = '%s:%s' % (virtual_environment_bin, env['PATH']) env['PYTHONPATH'] = python_path env.update( SANITY_IMPORT_DIR=os.path.relpath(temp_root, data_context().content.root) + os.path.sep, SANITY_MINIMAL_DIR=os.path.relpath(virtual_environment_path, data_context().content.root) + os.path.sep, ) virtualenv_python = os.path.join(virtual_environment_bin, 'python') virtualenv_pip = generate_pip_command(virtualenv_python) # make sure coverage is available in the virtual environment if needed if args.coverage: run_command(args, generate_pip_install(virtualenv_pip, 'sanity.import', packages=['setuptools']), env=env, capture=capture_pip) run_command(args, generate_pip_install(virtualenv_pip, 'sanity.import', packages=['coverage']), env=env, capture=capture_pip) run_command(args, virtualenv_pip + ['uninstall', '--disable-pip-version-check', '-y', 'setuptools'], env=env, capture=capture_pip) run_command(args, virtualenv_pip + ['uninstall', '--disable-pip-version-check', '-y', 'pip'], env=env, capture=capture_pip) cmd = ['importer.py'] data = '\n'.join(paths) display.info(data, verbosity=4) results = [] try: with coverage_context(args): stdout, stderr = intercept_command(args, cmd, self.name, env, capture=True, data=data, python_version=python_version, virtualenv=virtualenv_python) if stdout or stderr: raise SubprocessError(cmd, stdout=stdout, stderr=stderr) except SubprocessError as ex: if ex.status != 10 or ex.stderr or not ex.stdout: raise pattern = r'^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): (?P<message>.*)$' results = parse_to_list_of_dict(pattern, ex.stdout) relative_temp_root = os.path.relpath(temp_root, data_context().content.root) + os.path.sep results = [SanityMessage( message=r['message'], path=os.path.relpath(r['path'], relative_temp_root) if r['path'].startswith(relative_temp_root) else r['path'], line=int(r['line']), column=int(r['column']), ) for r in results] results = settings.process_errors(results, paths) if results: return SanityFailure(self.name, messages=results, python_version=python_version) return SanitySuccess(self.name, python_version=python_version)
closed
ansible/ansible
https://github.com/ansible/ansible
61,884
Import test doesn't recognize relative imports in a module inside collection
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When trying to check support of relative imports in modules inside collections, import sanity test fails giving below error ``` Running sanity test 'import' with Python 2.7 ERROR: Found 1 import issue(s) on python 2.7 which need to be resolved: ERROR: plugins/modules/rubrik_managed_volume.py:8:0: ValueError: Attempted relative import in non-package WARNING: Skipping sanity test 'import' on Python 3.5 due to missing interpreter. WARNING: Skipping sanity test 'import' on Python 3.6 due to missing interpreter. Running sanity test 'import' with Python 3.7 ERROR: Found 1 import issue(s) on python 3.7 which need to be resolved: ERROR: plugins/modules/rubrik_managed_volume.py:8:0: ImportError: attempted relative import with no known parent package ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ansible-test sanity import ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.0b1 config file = /home/abehl/.ansible/collections/ansible_collections/rubrikinc/rubrik/ansible.cfg configured module search path = ['/home/abehl/.ansible/collections/ansible_collections/rubrikinc/rubrik/library'] ansible python module location = /home/abehl/work/src/anshul_ansible/ansible/lib/ansible executable location = /home/abehl/work/src/anshul_ansible/ansible/bin/ansible python version = 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create a collection with modules having relative imports Try running ansible-test sanity on the same module <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Relative imports should pass ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> ansible import tests doesn't recognize relative import <!--- Paste verbatim command output between quotes --> ```paste below ```
https://github.com/ansible/ansible/issues/61884
https://github.com/ansible/ansible/pull/63830
b52d7155678017340fd39711b335ec2c582d6783
92ccdeac31902803c953792d9af929c7edf93f60
2019-09-05T19:06:11Z
python
2019-10-23T06:00:35Z
test/lib/ansible_test/_data/sanity/import/importer.py
#!/usr/bin/env python """Import the given python module(s) and report error(s) encountered.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type def main(): """ Main program function used to isolate globals from imported code. Changes to globals in imported modules on Python 2.7 will overwrite our own globals. """ import contextlib import os import re import sys import traceback import warnings import_dir = os.environ['SANITY_IMPORT_DIR'] minimal_dir = os.environ['SANITY_MINIMAL_DIR'] try: import importlib.util imp = None # pylint: disable=invalid-name except ImportError: importlib = None # pylint: disable=invalid-name import imp try: # noinspection PyCompatibility from StringIO import StringIO except ImportError: from io import StringIO import ansible.module_utils.basic import ansible.module_utils.common.removed try: from ansible.utils.collection_loader import AnsibleCollectionLoader except ImportError: # noinspection PyPep8Naming AnsibleCollectionLoader = None # These are the public attribute sof a doc-only module doc_keys = ('ANSIBLE_METADATA', 'DOCUMENTATION', 'EXAMPLES', 'RETURN', 'absolute_import', 'division', 'print_function') class ImporterAnsibleModuleException(Exception): """Exception thrown during initialization of ImporterAnsibleModule.""" class ImporterAnsibleModule: """Replacement for AnsibleModule to support import testing.""" def __init__(self, *args, **kwargs): raise ImporterAnsibleModuleException() # stop Ansible module execution during AnsibleModule instantiation ansible.module_utils.basic.AnsibleModule = ImporterAnsibleModule # no-op for _load_params since it may be called before instantiating AnsibleModule ansible.module_utils.basic._load_params = lambda *args, **kwargs: {} # pylint: disable=protected-access # no-op for removed_module since it is called in place of AnsibleModule instantiation ansible.module_utils.common.removed.removed_module = lambda *args, **kwargs: None def run(): """Main program function.""" base_dir = os.getcwd() messages = set() if AnsibleCollectionLoader: # allow importing code from collections # noinspection PyCallingNonCallable sys.meta_path.insert(0, AnsibleCollectionLoader()) for path in sys.argv[1:] or sys.stdin.read().splitlines(): test_python_module(path, base_dir, messages, False) test_python_module(path, base_dir, messages, True) if messages: exit(10) def test_python_module(path, base_dir, messages, ansible_module): if ansible_module: # importing modules with __main__ under Python 2.6 exits with status code 1 if sys.version_info < (2, 7): return # only run __main__ protected code for Ansible modules if not path.startswith('lib/ansible/modules/'): return # __init__ in module directories is empty (enforced by a different test) if path.endswith('__init__.py'): return # async_wrapper is not an Ansible module if path == 'lib/ansible/modules/utilities/logic/async_wrapper.py': return name = calculate_python_module_name(path) # show the Ansible module responsible for the exception, even if it was thrown in module_utils filter_dir = os.path.join(base_dir, 'lib/ansible/modules') else: # Calculate module name name = calculate_python_module_name(path) # show the Ansible file responsible for the exception, even if it was thrown in 3rd party code filter_dir = base_dir capture = Capture() try: if imp: with capture_output(capture): # On Python2 without absolute_import we have to import parent modules all # the way up the tree full_path = os.path.abspath(path) parent_mod = None py_packages = name.split('.') # BIG HACK: reimporting module_utils breaks the monkeypatching of basic we did # above and also breaks modules which import names directly from module_utils # modules (you'll get errors like ERROR: # lib/ansible/modules/storage/netapp/na_ontap_vserver_cifs_security.py:151:0: # AttributeError: 'module' object has no attribute 'netapp'). # So when we import a module_util here, use a munged name. if 'module_utils' in py_packages: # Avoid accidental double underscores by using _1 as a prefix py_packages[-1] = '_1%s' % py_packages[-1] name = '.'.join(py_packages) for idx in range(1, len(py_packages)): parent_name = '.'.join(py_packages[:idx]) if parent_mod is None: toplevel_end = full_path.find('ansible/module') toplevel = full_path[:toplevel_end] parent_mod_info = imp.find_module(parent_name, [toplevel]) else: parent_mod_info = imp.find_module(py_packages[idx - 1], parent_mod.__path__) parent_mod = imp.load_module(parent_name, *parent_mod_info) # skip distro due to an apparent bug or bad interaction in # imp.load_module() with our distro/__init__.py. # distro/__init__.py sets sys.modules['ansible.module_utils.distro'] # = _distro.pyc # but after running imp.load_module(), # sys.modules['ansible.module_utils.distro._distro'] = __init__.pyc # (The opposite of what we set) # This does not affect runtime so regular import seems to work. It's # just imp.load_module() if name == 'ansible.module_utils.distro._1__init__': return with open(path, 'r') as module_fd: module = imp.load_module(name, module_fd, full_path, ('.py', 'r', imp.PY_SOURCE)) if ansible_module: run_if_really_module(module) else: spec = importlib.util.spec_from_file_location(name, os.path.abspath(path)) module = importlib.util.module_from_spec(spec) with capture_output(capture): spec.loader.exec_module(module) if ansible_module: run_if_really_module(module) capture_report(path, capture, messages) except ImporterAnsibleModuleException: # module instantiated AnsibleModule without raising an exception pass # We truly want to catch anything the plugin might do here, including call sys.exit() so we # catch BaseException except BaseException as ex: # pylint: disable=locally-disabled, broad-except capture_report(path, capture, messages) exc_type, _exc, exc_tb = sys.exc_info() message = str(ex) results = list(reversed(traceback.extract_tb(exc_tb))) source = None line = 0 offset = 0 if isinstance(ex, SyntaxError) and ex.filename.endswith(path): # pylint: disable=locally-disabled, no-member # A SyntaxError in the source we're importing will have the correct path, line and offset. # However, the traceback will report the path to this importer.py script instead. # We'll use the details from the SyntaxError in this case, as it's more accurate. source = path line = ex.lineno or 0 # pylint: disable=locally-disabled, no-member offset = ex.offset or 0 # pylint: disable=locally-disabled, no-member message = str(ex) # Hack to remove the filename and line number from the message, if present. message = message.replace(' (%s, line %d)' % (os.path.basename(path), line), '') else: for result in results: if result[0].startswith(filter_dir): source = result[0][len(base_dir) + 1:].replace('test/lib/ansible_test/_data/sanity/import/', '') line = result[1] or 0 break if not source: # If none of our source files are found in the traceback, report the file we were testing. # I haven't been able to come up with a test case that encounters this issue yet. source = path message += ' (in %s:%d)' % (results[-1][0], results[-1][1] or 0) message = re.sub(r'\n *', ': ', message) error = '%s:%d:%d: %s: %s' % (source, line, offset, exc_type.__name__, message) report_message(error, messages) def run_if_really_module(module): # Module was removed if ('removed' not in module.ANSIBLE_METADATA['status'] and # Documentation only module [attr for attr in (frozenset(module.__dict__.keys()).difference(doc_keys)) if not (attr.startswith('__') and attr.endswith('__'))]): # Run main() code for ansible_modules module.main() def calculate_python_module_name(path): name = None try: idx = path.index('ansible/modules') except ValueError: try: idx = path.index('ansible/module_utils') except ValueError: try: idx = path.index('ansible_collections') except ValueError: # Default name = 'module_import_test' if name is None: name = path[idx:-len('.py')].replace('/', '.') return name class Capture: """Captured output and/or exception.""" def __init__(self): self.stdout = StringIO() self.stderr = StringIO() self.warnings = [] def capture_report(path, capture, messages): """Report on captured output. :type path: str :type capture: Capture :type messages: set[str] """ if capture.stdout.getvalue(): first = capture.stdout.getvalue().strip().splitlines()[0].strip() message = '%s:%d:%d: %s: %s' % (path, 0, 0, 'StandardOutputUsed', first) report_message(message, messages) if capture.stderr.getvalue(): first = capture.stderr.getvalue().strip().splitlines()[0].strip() message = '%s:%d:%d: %s: %s' % (path, 0, 0, 'StandardErrorUsed', first) report_message(message, messages) for warning in capture.warnings: msg = re.sub(r'\s+', ' ', '%s' % warning.message).strip() filepath = os.path.relpath(warning.filename) lineno = warning.lineno if filepath.startswith('../') or filepath.startswith(minimal_dir): # The warning occurred outside our source tree. # The best we can do is to report the file which was tested that triggered the warning. # If the responsible import is in shared code this warning will be repeated for each file tested which imports the shared code. msg += ' (in %s:%d)' % (warning.filename, warning.lineno) filepath = path lineno = 0 elif filepath.startswith(import_dir): # Strip the import dir from warning paths in shared code. # Needed when warnings occur in places like module_utils but are caught by the modules importing the module_utils. filepath = os.path.relpath(filepath, import_dir) message = '%s:%d:%d: %s: %s' % (filepath, lineno, 0, warning.category.__name__, msg) report_message(message, messages) def report_message(message, messages): """Report message if not already reported. :type message: str :type messages: set[str] """ if message not in messages: messages.add(message) print(message) @contextlib.contextmanager def capture_output(capture): """Capture sys.stdout and sys.stderr. :type capture: Capture """ old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = capture.stdout sys.stderr = capture.stderr with warnings.catch_warnings(record=True) as captured_warnings: try: yield finally: capture.warnings = captured_warnings sys.stdout = old_stdout sys.stderr = old_stderr run() if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,884
Import test doesn't recognize relative imports in a module inside collection
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When trying to check support of relative imports in modules inside collections, import sanity test fails giving below error ``` Running sanity test 'import' with Python 2.7 ERROR: Found 1 import issue(s) on python 2.7 which need to be resolved: ERROR: plugins/modules/rubrik_managed_volume.py:8:0: ValueError: Attempted relative import in non-package WARNING: Skipping sanity test 'import' on Python 3.5 due to missing interpreter. WARNING: Skipping sanity test 'import' on Python 3.6 due to missing interpreter. Running sanity test 'import' with Python 3.7 ERROR: Found 1 import issue(s) on python 3.7 which need to be resolved: ERROR: plugins/modules/rubrik_managed_volume.py:8:0: ImportError: attempted relative import with no known parent package ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ansible-test sanity import ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.0b1 config file = /home/abehl/.ansible/collections/ansible_collections/rubrikinc/rubrik/ansible.cfg configured module search path = ['/home/abehl/.ansible/collections/ansible_collections/rubrikinc/rubrik/library'] ansible python module location = /home/abehl/work/src/anshul_ansible/ansible/lib/ansible executable location = /home/abehl/work/src/anshul_ansible/ansible/bin/ansible python version = 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create a collection with modules having relative imports Try running ansible-test sanity on the same module <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Relative imports should pass ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> ansible import tests doesn't recognize relative import <!--- Paste verbatim command output between quotes --> ```paste below ```
https://github.com/ansible/ansible/issues/61884
https://github.com/ansible/ansible/pull/63830
b52d7155678017340fd39711b335ec2c582d6783
92ccdeac31902803c953792d9af929c7edf93f60
2019-09-05T19:06:11Z
python
2019-10-23T06:00:35Z
test/lib/ansible_test/_internal/sanity/import.py
"""Sanity test for proper import exception handling.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from .. import types as t from ..sanity import ( SanityMultipleVersion, SanityMessage, SanityFailure, SanitySuccess, SanitySkipped, SANITY_ROOT, ) from ..target import ( TestTarget, ) from ..util import ( SubprocessError, remove_tree, display, parse_to_list_of_dict, is_subdir, ANSIBLE_LIB_ROOT, generate_pip_command, find_python, ) from ..util_common import ( intercept_command, run_command, write_text_file, ResultType, ) from ..ansible_util import ( ansible_environment, ) from ..executor import ( generate_pip_install, ) from ..config import ( SanityConfig, ) from ..coverage_util import ( coverage_context, ) from ..venv import ( create_virtual_environment, ) from ..data import ( data_context, ) class ImportTest(SanityMultipleVersion): """Sanity test for proper import exception handling.""" def filter_targets(self, targets): # type: (t.List[TestTarget]) -> t.List[TestTarget] """Return the given list of test targets, filtered to include only those relevant for the test.""" return [target for target in targets if os.path.splitext(target.path)[1] == '.py' and (is_subdir(target.path, data_context().content.module_path) or is_subdir(target.path, data_context().content.module_utils_path))] def test(self, args, targets, python_version): """ :type args: SanityConfig :type targets: SanityTargets :type python_version: str :rtype: TestResult """ capture_pip = args.verbosity < 2 if python_version.startswith('2.') and args.requirements: # hack to make sure that virtualenv is available under Python 2.x # on Python 3.x we can use the built-in venv pip = generate_pip_command(find_python(python_version)) run_command(args, generate_pip_install(pip, 'sanity.import', packages=['virtualenv']), capture=capture_pip) settings = self.load_processor(args, python_version) paths = [target.path for target in targets.include] env = ansible_environment(args, color=False) temp_root = os.path.join(ResultType.TMP.path, 'sanity', 'import') # create a clean virtual environment to minimize the available imports beyond the python standard library virtual_environment_path = os.path.join(temp_root, 'minimal-py%s' % python_version.replace('.', '')) virtual_environment_bin = os.path.join(virtual_environment_path, 'bin') remove_tree(virtual_environment_path) if not create_virtual_environment(args, python_version, virtual_environment_path): display.warning("Skipping sanity test '%s' on Python %s due to missing virtual environment support." % (self.name, python_version)) return SanitySkipped(self.name, python_version) # add the importer to our virtual environment so it can be accessed through the coverage injector importer_path = os.path.join(virtual_environment_bin, 'importer.py') if not args.explain: os.symlink(os.path.abspath(os.path.join(SANITY_ROOT, 'import', 'importer.py')), importer_path) # create a minimal python library python_path = os.path.join(temp_root, 'lib') ansible_path = os.path.join(python_path, 'ansible') ansible_init = os.path.join(ansible_path, '__init__.py') ansible_link = os.path.join(ansible_path, 'module_utils') if not args.explain: remove_tree(ansible_path) write_text_file(ansible_init, '', create_directories=True) os.symlink(os.path.join(ANSIBLE_LIB_ROOT, 'module_utils'), ansible_link) if data_context().content.collection: # inject just enough Ansible code for the collections loader to work on all supported Python versions # the __init__.py files are needed only for Python 2.x # the empty modules directory is required for the collection loader to generate the synthetic packages list write_text_file(os.path.join(ansible_path, 'utils/__init__.py'), '', create_directories=True) os.symlink(os.path.join(ANSIBLE_LIB_ROOT, 'utils', 'collection_loader.py'), os.path.join(ansible_path, 'utils', 'collection_loader.py')) os.symlink(os.path.join(ANSIBLE_LIB_ROOT, 'utils', 'singleton.py'), os.path.join(ansible_path, 'utils', 'singleton.py')) write_text_file(os.path.join(ansible_path, 'modules/__init__.py'), '', create_directories=True) # activate the virtual environment env['PATH'] = '%s:%s' % (virtual_environment_bin, env['PATH']) env['PYTHONPATH'] = python_path env.update( SANITY_IMPORT_DIR=os.path.relpath(temp_root, data_context().content.root) + os.path.sep, SANITY_MINIMAL_DIR=os.path.relpath(virtual_environment_path, data_context().content.root) + os.path.sep, ) virtualenv_python = os.path.join(virtual_environment_bin, 'python') virtualenv_pip = generate_pip_command(virtualenv_python) # make sure coverage is available in the virtual environment if needed if args.coverage: run_command(args, generate_pip_install(virtualenv_pip, 'sanity.import', packages=['setuptools']), env=env, capture=capture_pip) run_command(args, generate_pip_install(virtualenv_pip, 'sanity.import', packages=['coverage']), env=env, capture=capture_pip) run_command(args, virtualenv_pip + ['uninstall', '--disable-pip-version-check', '-y', 'setuptools'], env=env, capture=capture_pip) run_command(args, virtualenv_pip + ['uninstall', '--disable-pip-version-check', '-y', 'pip'], env=env, capture=capture_pip) cmd = ['importer.py'] data = '\n'.join(paths) display.info(data, verbosity=4) results = [] try: with coverage_context(args): stdout, stderr = intercept_command(args, cmd, self.name, env, capture=True, data=data, python_version=python_version, virtualenv=virtualenv_python) if stdout or stderr: raise SubprocessError(cmd, stdout=stdout, stderr=stderr) except SubprocessError as ex: if ex.status != 10 or ex.stderr or not ex.stdout: raise pattern = r'^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): (?P<message>.*)$' results = parse_to_list_of_dict(pattern, ex.stdout) relative_temp_root = os.path.relpath(temp_root, data_context().content.root) + os.path.sep results = [SanityMessage( message=r['message'], path=os.path.relpath(r['path'], relative_temp_root) if r['path'].startswith(relative_temp_root) else r['path'], line=int(r['line']), column=int(r['column']), ) for r in results] results = settings.process_errors(results, paths) if results: return SanityFailure(self.name, messages=results, python_version=python_version) return SanitySuccess(self.name, python_version=python_version)
closed
ansible/ansible
https://github.com/ansible/ansible
63,777
ios_facts l2_interfaces resource only returning Gig interfaces
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> I have been using 2.9.0rc4 to try out the new resource models for ios_facts and the l2_interfaces resource only parses Gigabit interfaces and completely ignores other interface (Fast (100 Mbps), Ten, Twenty, Forty, Hundred etc.) Line 89 in the module says `if intf.lower().startswith('gi'):` If I remove the if statement I get all interfaces including Vlan interfaces which definitily shouldn't be parsed. I would like to discuss if this should be replaced with a whitelist which needs to be kept updated or a blacklist to exclude unwanted interfaces. I can open a PR later to fix it when a decision has been made how to filter ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ios_facts ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.0rc4 config file = /home/dennis/.ansible.cfg configured module search path = [u'/home/dennis/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.13 (default, Sep 26 2018, 18:42:22) [GCC 6.3.0 20170516] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below DEFAULT_FORKS(/home/dennis/.ansible.cfg) = 4 DEFAULT_STDOUT_CALLBACK(/home/dennis/.ansible.cfg) = yaml HOST_KEY_CHECKING(/home/dennis/.ansible.cfg) = False INTERPRETER_PYTHON(/home/dennis/.ansible.cfg) = auto_legacy_silent INVENTORY_ENABLED(/home/dennis/.ansible.cfg) = [u'yaml'] RETRY_FILES_ENABLED(/home/dennis/.ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Host: Debian via WSL Switch: Cisco C2960 running IOS 15.0(2) ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> ansible -m ios_facts switch_hostname -a "gather_network_resources=l2_interfaces" <!--- Paste example playbooks or commands between quotes below --> <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ```yaml ansible_facts: ansible_net_gather_network_resources: - l2_interfaces ansible_net_gather_subset: [] ansible_network_resources: l2_interfaces: - name: FastEthernet0/1 - name: FastEthernet0/2 - name: FastEthernet0/3 - access: vlan: 569 name: FastEthernet0/4 - name: FastEthernet0/5 - name: FastEthernet0/6 - name: FastEthernet0/7 - name: FastEthernet0/8 - name: FastEthernet0/9 - name: FastEthernet0/10 - name: FastEthernet0/11 - name: FastEthernet0/12 - name: FastEthernet0/13 - name: FastEthernet0/14 - name: FastEthernet0/15 - name: FastEthernet0/16 - name: FastEthernet0/17 - name: FastEthernet0/18 - name: FastEthernet0/19 - name: FastEthernet0/20 - name: FastEthernet0/21 - name: FastEthernet0/22 - name: FastEthernet0/23 - name: FastEthernet0/24 - name: FastEthernet0/25 - name: FastEthernet0/26 - name: FastEthernet0/27 - name: FastEthernet0/28 - name: FastEthernet0/29 - name: FastEthernet0/30 - name: FastEthernet0/31 - name: FastEthernet0/32 - name: FastEthernet0/33 - name: FastEthernet0/34 - name: FastEthernet0/35 - name: FastEthernet0/36 - name: FastEthernet0/37 - name: FastEthernet0/38 - access: vlan: 3033 name: FastEthernet0/39 - name: FastEthernet0/40 - name: FastEthernet0/41 - name: FastEthernet0/42 - name: FastEthernet0/43 - name: FastEthernet0/44 - name: FastEthernet0/45 - name: FastEthernet0/46 - name: FastEthernet0/47 - name: FastEthernet0/48 - name: GigabitEthernet0/1 - name: GigabitEthernet0/2 discovered_interpreter_python: /usr/bin/python ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> ```yaml ansible_facts: ansible_net_gather_network_resources: - l2_interfaces ansible_net_gather_subset: [] ansible_network_resources: l2_interfaces: - name: GigabitEthernet0/1 - name: GigabitEthernet0/2 discovered_interpreter_python: /usr/bin/python ```
https://github.com/ansible/ansible/issues/63777
https://github.com/ansible/ansible/pull/63779
3e4ae4225688c02190a00cd1818136d8e09f3a16
d620a209a5935aff190e74057ad4e30fa9dcefb4
2019-10-22T10:51:41Z
python
2019-10-23T15:43:37Z
lib/ansible/module_utils/network/ios/facts/l2_interfaces/l2_interfaces.py
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The ios interfaces fact class It is in this file the configuration is collected from the device for a given resource, parsed, and the facts tree is populated based on the configuration. """ from __future__ import absolute_import, division, print_function __metaclass__ = type from copy import deepcopy import re from ansible.module_utils.network.common import utils from ansible.module_utils.network.ios.utils.utils import get_interface_type, normalize_interface from ansible.module_utils.network.ios.argspec.l2_interfaces.l2_interfaces import L2_InterfacesArgs class L2_InterfacesFacts(object): """ The ios l2 interfaces fact class """ def __init__(self, module, subspec='config', options='options'): self._module = module self.argument_spec = L2_InterfacesArgs.argument_spec spec = deepcopy(self.argument_spec) if subspec: if options: facts_argument_spec = spec[subspec][options] else: facts_argument_spec = spec[subspec] else: facts_argument_spec = spec self.generated_spec = utils.generate_dict(facts_argument_spec) def populate_facts(self, connection, ansible_facts, data=None): """ Populate the facts for interfaces :param connection: the device connection :param ansible_facts: Facts dictionary :param data: previously collected conf :rtype: dictionary :returns: facts """ objs = [] if not data: data = connection.get('show running-config | section ^interface') # operate on a collection of resource x config = data.split('interface ') for conf in config: if conf: obj = self.render_config(self.generated_spec, conf) if obj: objs.append(obj) facts = {} if objs: facts['l2_interfaces'] = [] params = utils.validate_config(self.argument_spec, {'config': objs}) for cfg in params['config']: facts['l2_interfaces'].append(utils.remove_empties(cfg)) ansible_facts['ansible_network_resources'].update(facts) return ansible_facts def render_config(self, spec, conf): """ Render config as dictionary structure and delete keys from spec for null values :param spec: The facts tree, generated from the argspec :param conf: The configuration :rtype: dictionary :returns: The generated config """ config = deepcopy(spec) match = re.search(r'^(\S+)', conf) intf = match.group(1) if get_interface_type(intf) == 'unknown': return {} if intf.lower().startswith('gi'): # populate the facts from the configuration config['name'] = normalize_interface(intf) has_access = utils.parse_conf_arg(conf, 'switchport access vlan') if has_access: config["access"] = {"vlan": int(has_access)} trunk = dict() trunk["encapsulation"] = utils.parse_conf_arg(conf, 'encapsulation') native_vlan = utils.parse_conf_arg(conf, 'native vlan') if native_vlan: trunk["native_vlan"] = int(native_vlan) allowed_vlan = utils.parse_conf_arg(conf, 'allowed vlan') if allowed_vlan: trunk["allowed_vlans"] = allowed_vlan.split(',') pruning_vlan = utils.parse_conf_arg(conf, 'pruning vlan') if pruning_vlan: trunk['pruning_vlans'] = pruning_vlan.split(',') config['trunk'] = trunk return utils.remove_empties(config)
closed
ansible/ansible
https://github.com/ansible/ansible
63,683
dnf module crashes when omitting a specific appstream version
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Reading the [dnf module documentation](https://docs.ansible.com/ansible/latest/modules/dnf_module.html), I should be able to install a yum module just specifing an appstream module name with a profile without the need to specify an appstream version. But if you omit the appstream version, the dnf ansible plugin crashes with a strack-trace ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME dnf ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible-playbook 2.8.6 config file = /home/ansible/.virtualenvs/ansb28/ansible.cfg configured module search path = [u'/home/ansible/ansb28/ansible/library'] ansible python module location = /home/ansible/.virtualenvs/ansb28/lib/python2.7/site-packages/ansible executable location = /home/ansible/.virtualenvs/ansb28/bin/ansible-playbook python version = 2.7.5 (default, Sep 15 2016, 22:37:39) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_NOCOWS(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = True DEFAULT_CALLBACK_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/lib/python2.7/site-packages/ara/plugins/callbacks'] DEFAULT_CALLBACK_WHITELIST(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'ara'] DEFAULT_INVENTORY_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/ansible/plugins/inventory'] DEFAULT_MODULE_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/ansb28/ansible/library'] DEFAULT_ROLES_PATH(env: ANSIBLE_ROLES_PATH) = [u'/home/ansible/infra/roles'] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> management host: CentOS 7 target host: CentOS 8 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Try to run the following task against a CentOS 8 host: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Install rhn-client and other required packages (EL8) dnf: name: "@satellite-5-client/common" state: present when: ansible_distribution_major_version == "8" ``` The task fails with the following stacktrace: ``` centos8 | FAILED! => { "changed": false, "module_stderr": "Shared connection to 10.4.2.130 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/usr/lib/python3.6/site-packages/dnf/plugin.py\", line 102, in _caller\r\n getattr(plugin, method)()\r\n File \"/usr/lib/python3.6/site-packages/dnf-plugins/spacewalk.py\", line 84, in config\r\n self.cli.demands.root_user = True\r\nAttributeError: 'NoneType' object has no attribute 'demands'\r\n\r\nTraceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 114, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 106, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 49, in invoke_module\r\n imp.load_module('__main__', mod, module, MOD_DESC)\r\n File \"/usr/lib64/python3.6/imp.py\", line 235, in load_module\r\n return load_source(name, filename, file)\r\n File \"/usr/lib64/python3.6/imp.py\", line 170, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 618, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1322, in <module>\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1311, in main\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1290, in run\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 957, in ensure\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 890, in _is_module_installed\r\nTypeError: 'in <string>' requires string as left operand, not NoneType\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The appstream module is installed using the default module version without the need to specify it. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The dnf module crashes <!--- Paste verbatim command output between quotes --> ```paste below ```
https://github.com/ansible/ansible/issues/63683
https://github.com/ansible/ansible/pull/63819
b96ae6ab676744264a3915d57fd2fb9454e57384
ed86907587140daa933d8db08c7dca473757a63a
2019-10-18T13:35:31Z
python
2019-10-24T04:57:31Z
changelogs/fragments/63683-dnf-handle-empty-appstream-stream.yml
closed
ansible/ansible
https://github.com/ansible/ansible
63,683
dnf module crashes when omitting a specific appstream version
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Reading the [dnf module documentation](https://docs.ansible.com/ansible/latest/modules/dnf_module.html), I should be able to install a yum module just specifing an appstream module name with a profile without the need to specify an appstream version. But if you omit the appstream version, the dnf ansible plugin crashes with a strack-trace ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME dnf ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible-playbook 2.8.6 config file = /home/ansible/.virtualenvs/ansb28/ansible.cfg configured module search path = [u'/home/ansible/ansb28/ansible/library'] ansible python module location = /home/ansible/.virtualenvs/ansb28/lib/python2.7/site-packages/ansible executable location = /home/ansible/.virtualenvs/ansb28/bin/ansible-playbook python version = 2.7.5 (default, Sep 15 2016, 22:37:39) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_NOCOWS(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = True DEFAULT_CALLBACK_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/lib/python2.7/site-packages/ara/plugins/callbacks'] DEFAULT_CALLBACK_WHITELIST(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'ara'] DEFAULT_INVENTORY_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/ansible/plugins/inventory'] DEFAULT_MODULE_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/ansb28/ansible/library'] DEFAULT_ROLES_PATH(env: ANSIBLE_ROLES_PATH) = [u'/home/ansible/infra/roles'] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> management host: CentOS 7 target host: CentOS 8 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Try to run the following task against a CentOS 8 host: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Install rhn-client and other required packages (EL8) dnf: name: "@satellite-5-client/common" state: present when: ansible_distribution_major_version == "8" ``` The task fails with the following stacktrace: ``` centos8 | FAILED! => { "changed": false, "module_stderr": "Shared connection to 10.4.2.130 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/usr/lib/python3.6/site-packages/dnf/plugin.py\", line 102, in _caller\r\n getattr(plugin, method)()\r\n File \"/usr/lib/python3.6/site-packages/dnf-plugins/spacewalk.py\", line 84, in config\r\n self.cli.demands.root_user = True\r\nAttributeError: 'NoneType' object has no attribute 'demands'\r\n\r\nTraceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 114, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 106, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 49, in invoke_module\r\n imp.load_module('__main__', mod, module, MOD_DESC)\r\n File \"/usr/lib64/python3.6/imp.py\", line 235, in load_module\r\n return load_source(name, filename, file)\r\n File \"/usr/lib64/python3.6/imp.py\", line 170, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 618, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1322, in <module>\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1311, in main\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1290, in run\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 957, in ensure\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 890, in _is_module_installed\r\nTypeError: 'in <string>' requires string as left operand, not NoneType\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The appstream module is installed using the default module version without the need to specify it. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The dnf module crashes <!--- Paste verbatim command output between quotes --> ```paste below ```
https://github.com/ansible/ansible/issues/63683
https://github.com/ansible/ansible/pull/63819
b96ae6ab676744264a3915d57fd2fb9454e57384
ed86907587140daa933d8db08c7dca473757a63a
2019-10-18T13:35:31Z
python
2019-10-24T04:57:31Z
lib/ansible/modules/packaging/os/dnf.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2015 Cristian van Ee <cristian at cvee.org> # Copyright 2015 Igor Gnatenko <[email protected]> # Copyright 2018 Adam Miller <[email protected]> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: dnf version_added: 1.9 short_description: Manages packages with the I(dnf) package manager description: - Installs, upgrade, removes, and lists packages and groups with the I(dnf) package manager. options: name: description: - "A package name or package specifier with version, like C(name-1.0). When using state=latest, this can be '*' which means run: dnf -y update. You can also pass a url or a local path to a rpm file. To operate on several packages this can accept a comma separated string of packages or a list of packages." required: true aliases: - pkg list: description: - Various (non-idempotent) commands for usage with C(/usr/bin/ansible) and I(not) playbooks. See examples. state: description: - Whether to install (C(present), C(latest)), or remove (C(absent)) a package. - Default is C(None), however in effect the default action is C(present) unless the C(autoremove) option is enabled for this module, then C(absent) is inferred. choices: ['absent', 'present', 'installed', 'removed', 'latest'] enablerepo: description: - I(Repoid) of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a ",". disablerepo: description: - I(Repoid) of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a ",". conf_file: description: - The remote dnf configuration file to use for the transaction. disable_gpg_check: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). type: bool default: 'no' installroot: description: - Specifies an alternative installroot, relative to which all packages will be installed. version_added: "2.3" default: "/" releasever: description: - Specifies an alternative release from which all packages will be installed. version_added: "2.6" autoremove: description: - If C(yes), removes all "leaf" packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when state is I(absent) type: bool default: "no" version_added: "2.4" exclude: description: - Package name(s) to exclude when state=present, or latest. This can be a list or a comma separated string. version_added: "2.7" skip_broken: description: - Skip packages with broken dependencies(devsolve) and are causing problems. type: bool default: "no" version_added: "2.7" update_cache: description: - Force dnf to check if cache is out of date and redownload if needed. Has an effect only if state is I(present) or I(latest). type: bool default: "no" aliases: [ expire-cache ] version_added: "2.7" update_only: description: - When using latest, only update installed packages. Do not install packages. - Has an effect only if state is I(latest) default: "no" type: bool version_added: "2.7" security: description: - If set to C(yes), and C(state=latest) then only installs updates that have been marked security related. type: bool default: "no" version_added: "2.7" bugfix: description: - If set to C(yes), and C(state=latest) then only installs updates that have been marked bugfix related. default: "no" type: bool version_added: "2.7" enable_plugin: description: - I(Plugin) name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction. version_added: "2.7" disable_plugin: description: - I(Plugin) name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction. version_added: "2.7" disable_excludes: description: - Disable the excludes defined in DNF config files. - If set to C(all), disables all excludes. - If set to C(main), disable excludes defined in [main] in dnf.conf. - If set to C(repoid), disable excludes defined for given repo id. version_added: "2.7" validate_certs: description: - This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to C(no), the SSL certificates will not be validated. - This should only set to C(no) used on personally controlled sites using self-signed certificates as it avoids verifying the source site. type: bool default: "yes" version_added: "2.7" allow_downgrade: description: - Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction). type: bool default: "no" version_added: "2.7" install_repoquery: description: - This is effectively a no-op in DNF as it is not needed with DNF, but is an accepted parameter for feature parity/compatibility with the I(yum) module. type: bool default: "yes" version_added: "2.7" download_only: description: - Only download the packages, do not install them. default: "no" type: bool version_added: "2.7" lock_timeout: description: - Amount of time to wait for the dnf lockfile to be freed. required: false default: 30 type: int version_added: "2.8" install_weak_deps: description: - Will also install all packages linked by a weak dependency relation. type: bool default: "yes" version_added: "2.8" download_dir: description: - Specifies an alternate directory to store packages. - Has an effect only if I(download_only) is specified. type: str version_added: "2.8" notes: - When used with a `loop:` each package will be processed individually, it is much more efficient to pass the list directly to the `name` option. - Group removal doesn't work if the group was installed with Ansible because upstream dnf's API doesn't properly mark groups as installed, therefore upon removal the module is unable to detect that the group is installed (https://bugzilla.redhat.com/show_bug.cgi?id=1620324) requirements: - "python >= 2.6" - python-dnf - for the autoremove option you need dnf >= 2.0.1" author: - Igor Gnatenko (@ignatenkobrain) <[email protected]> - Cristian van Ee (@DJMuggs) <cristian at cvee.org> - Berend De Schouwer (@berenddeschouwer) - Adam Miller (@maxamillion) <[email protected]> ''' EXAMPLES = ''' - name: install the latest version of Apache dnf: name: httpd state: latest - name: install the latest version of Apache and MariaDB dnf: name: - httpd - mariadb-server state: latest - name: remove the Apache package dnf: name: httpd state: absent - name: install the latest version of Apache from the testing repo dnf: name: httpd enablerepo: testing state: present - name: upgrade all packages dnf: name: "*" state: latest - name: install the nginx rpm from a remote repo dnf: name: 'http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm' state: present - name: install nginx rpm from a local file dnf: name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state: present - name: install the 'Development tools' package group dnf: name: '@Development tools' state: present - name: Autoremove unneeded packages installed as dependencies dnf: autoremove: yes - name: Uninstall httpd but keep its dependencies dnf: name: httpd state: absent autoremove: no - name: install a modularity appstream with defined stream and profile dnf: name: '@postgresql:9.6/client' state: present - name: install a modularity appstream with defined stream dnf: name: '@postgresql:9.6' state: present - name: install a modularity appstream with defined profile dnf: name: '@postgresql/client' state: present ''' import os import re import sys import tempfile try: import dnf import dnf.cli import dnf.const import dnf.exceptions import dnf.subject import dnf.util HAS_DNF = True except ImportError: HAS_DNF = False from ansible.module_utils._text import to_native, to_text from ansible.module_utils.urls import fetch_url from ansible.module_utils.six import PY2, text_type from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.yumdnf import YumDnf, yumdnf_argument_spec # 64k. Number of bytes to read at a time when manually downloading pkgs via a url BUFSIZE = 65536 class DnfModule(YumDnf): """ DNF Ansible module back-end implementation """ def __init__(self, module): # This populates instance vars for all argument spec params super(DnfModule, self).__init__(module) self._ensure_dnf() self.lockfile = "/var/cache/dnf/*_lock.pid" self.pkg_mgr_name = "dnf" try: self.with_modules = dnf.base.WITH_MODULES except AttributeError: self.with_modules = False def is_lockfile_pid_valid(self): # FIXME? it looks like DNF takes care of invalid lock files itself? # https://github.com/ansible/ansible/issues/57189 return True def _sanitize_dnf_error_msg_install(self, spec, error): """ For unhandled dnf.exceptions.Error scenarios, there are certain error messages we want to filter in an install scenario. Do that here. """ if to_text("no package matched") in to_text(error): return "No package {0} available.".format(spec) return error def _sanitize_dnf_error_msg_remove(self, spec, error): """ For unhandled dnf.exceptions.Error scenarios, there are certain error messages we want to ignore in a removal scenario as known benign failures. Do that here. """ if 'no package matched' in to_native(error): return (False, "{0} is not installed".format(spec)) # Return value is tuple of: # ("Is this actually a failure?", "Error Message") return (True, error) def _package_dict(self, package): """Return a dictionary of information for the package.""" # NOTE: This no longer contains the 'dnfstate' field because it is # already known based on the query type. result = { 'name': package.name, 'arch': package.arch, 'epoch': str(package.epoch), 'release': package.release, 'version': package.version, 'repo': package.repoid} result['nevra'] = '{epoch}:{name}-{version}-{release}.{arch}'.format( **result) if package.installtime == 0: result['yumstate'] = 'available' else: result['yumstate'] = 'installed' return result def _packagename_dict(self, packagename): """ Return a dictionary of information for a package name string or None if the package name doesn't contain at least all NVR elements """ if packagename[-4:] == '.rpm': packagename = packagename[:-4] # This list was auto generated on a Fedora 28 system with the following one-liner # printf '[ '; for arch in $(ls /usr/lib/rpm/platform); do printf '"%s", ' ${arch%-linux}; done; printf ']\n' redhat_rpm_arches = [ "aarch64", "alphaev56", "alphaev5", "alphaev67", "alphaev6", "alpha", "alphapca56", "amd64", "armv3l", "armv4b", "armv4l", "armv5tejl", "armv5tel", "armv5tl", "armv6hl", "armv6l", "armv7hl", "armv7hnl", "armv7l", "athlon", "geode", "i386", "i486", "i586", "i686", "ia32e", "ia64", "m68k", "mips64el", "mips64", "mips64r6el", "mips64r6", "mipsel", "mips", "mipsr6el", "mipsr6", "noarch", "pentium3", "pentium4", "ppc32dy4", "ppc64iseries", "ppc64le", "ppc64", "ppc64p7", "ppc64pseries", "ppc8260", "ppc8560", "ppciseries", "ppc", "ppcpseries", "riscv64", "s390", "s390x", "sh3", "sh4a", "sh4", "sh", "sparc64", "sparc64v", "sparc", "sparcv8", "sparcv9", "sparcv9v", "x86_64" ] rpm_arch_re = re.compile(r'(.*)\.(.*)') rpm_nevr_re = re.compile(r'(\S+)-(?:(\d*):)?(.*)-(~?\w+[\w.+]*)') try: arch = None rpm_arch_match = rpm_arch_re.match(packagename) if rpm_arch_match: nevr, arch = rpm_arch_match.groups() if arch in redhat_rpm_arches: packagename = nevr rpm_nevr_match = rpm_nevr_re.match(packagename) if rpm_nevr_match: name, epoch, version, release = rpm_nevr_re.match(packagename).groups() if not version or not version.split('.')[0].isdigit(): return None else: return None except AttributeError as e: self.module.fail_json( msg='Error attempting to parse package: %s, %s' % (packagename, to_native(e)), rc=1, results=[] ) if not epoch: epoch = "0" if ':' in name: epoch_name = name.split(":") epoch = epoch_name[0] name = ''.join(epoch_name[1:]) result = { 'name': name, 'epoch': epoch, 'release': release, 'version': version, } return result # Original implementation from yum.rpmUtils.miscutils (GPLv2+) # http://yum.baseurl.org/gitweb?p=yum.git;a=blob;f=rpmUtils/miscutils.py def _compare_evr(self, e1, v1, r1, e2, v2, r2): # return 1: a is newer than b # 0: a and b are the same version # -1: b is newer than a if e1 is None: e1 = '0' else: e1 = str(e1) v1 = str(v1) r1 = str(r1) if e2 is None: e2 = '0' else: e2 = str(e2) v2 = str(v2) r2 = str(r2) # print '%s, %s, %s vs %s, %s, %s' % (e1, v1, r1, e2, v2, r2) rc = dnf.rpm.rpm.labelCompare((e1, v1, r1), (e2, v2, r2)) # print '%s, %s, %s vs %s, %s, %s = %s' % (e1, v1, r1, e2, v2, r2, rc) return rc def fetch_rpm_from_url(self, spec): # FIXME: Remove this once this PR is merged: # https://github.com/ansible/ansible/pull/19172 # download package so that we can query it package_name, dummy = os.path.splitext(str(spec.rsplit('/', 1)[1])) package_file = tempfile.NamedTemporaryFile(dir=self.module.tmpdir, prefix=package_name, suffix='.rpm', delete=False) self.module.add_cleanup_file(package_file.name) try: rsp, info = fetch_url(self.module, spec) if not rsp: self.module.fail_json( msg="Failure downloading %s, %s" % (spec, info['msg']), results=[], ) data = rsp.read(BUFSIZE) while data: package_file.write(data) data = rsp.read(BUFSIZE) package_file.close() except Exception as e: self.module.fail_json( msg="Failure downloading %s, %s" % (spec, to_native(e)), results=[], ) return package_file.name def _ensure_dnf(self): if not HAS_DNF: if PY2: package = 'python2-dnf' else: package = 'python3-dnf' if self.module.check_mode: self.module.fail_json( msg="`{0}` is not installed, but it is required" "for the Ansible dnf module.".format(package), results=[], ) rc, stdout, stderr = self.module.run_command(['dnf', 'install', '-y', package]) global dnf try: import dnf import dnf.cli import dnf.const import dnf.exceptions import dnf.subject import dnf.util except ImportError: self.module.fail_json( msg="Could not import the dnf python module using {0} ({1}). " "Please install `{2}` package or ensure you have specified the " "correct ansible_python_interpreter.".format(sys.executable, sys.version.replace('\n', ''), package), results=[], cmd='dnf install -y {0}'.format(package), rc=rc, stdout=stdout, stderr=stderr, ) def _configure_base(self, base, conf_file, disable_gpg_check, installroot='/'): """Configure the dnf Base object.""" conf = base.conf # Change the configuration file path if provided, this must be done before conf.read() is called if conf_file: # Fail if we can't read the configuration file. if not os.access(conf_file, os.R_OK): self.module.fail_json( msg="cannot read configuration file", conf_file=conf_file, results=[], ) else: conf.config_file_path = conf_file # Read the configuration file conf.read() # Turn off debug messages in the output conf.debuglevel = 0 # Set whether to check gpg signatures conf.gpgcheck = not disable_gpg_check conf.localpkg_gpgcheck = not disable_gpg_check # Don't prompt for user confirmations conf.assumeyes = True # Set installroot conf.installroot = installroot # Load substitutions from the filesystem conf.substitutions.update_from_etc(installroot) # Handle different DNF versions immutable mutable datatypes and # dnf v1/v2/v3 # # In DNF < 3.0 are lists, and modifying them works # In DNF >= 3.0 < 3.6 are lists, but modifying them doesn't work # In DNF >= 3.6 have been turned into tuples, to communicate that modifying them doesn't work # # https://www.happyassassin.net/2018/06/27/adams-debugging-adventures-the-immutable-mutable-object/ # # Set excludes if self.exclude: _excludes = list(conf.exclude) _excludes.extend(self.exclude) conf.exclude = _excludes # Set disable_excludes if self.disable_excludes: _disable_excludes = list(conf.disable_excludes) if self.disable_excludes not in _disable_excludes: _disable_excludes.append(self.disable_excludes) conf.disable_excludes = _disable_excludes # Set releasever if self.releasever is not None: conf.substitutions['releasever'] = self.releasever # Set skip_broken (in dnf this is strict=0) if self.skip_broken: conf.strict = 0 if self.download_only: conf.downloadonly = True if self.download_dir: conf.destdir = self.download_dir # Default in dnf upstream is true conf.clean_requirements_on_remove = self.autoremove # Default in dnf (and module default) is True conf.install_weak_deps = self.install_weak_deps def _specify_repositories(self, base, disablerepo, enablerepo): """Enable and disable repositories matching the provided patterns.""" base.read_all_repos() repos = base.repos # Disable repositories for repo_pattern in disablerepo: if repo_pattern: for repo in repos.get_matching(repo_pattern): repo.disable() # Enable repositories for repo_pattern in enablerepo: if repo_pattern: for repo in repos.get_matching(repo_pattern): repo.enable() def _base(self, conf_file, disable_gpg_check, disablerepo, enablerepo, installroot): """Return a fully configured dnf Base object.""" base = dnf.Base() self._configure_base(base, conf_file, disable_gpg_check, installroot) try: base.init_plugins(set(self.disable_plugin), set(self.enable_plugin)) base.pre_configure_plugins() except AttributeError: pass # older versions of dnf didn't require this and don't have these methods self._specify_repositories(base, disablerepo, enablerepo) try: base.configure_plugins() except AttributeError: pass # older versions of dnf didn't require this and don't have these methods try: if self.update_cache: try: base.update_cache() except dnf.exceptions.RepoError as e: self.module.fail_json( msg="{0}".format(to_text(e)), results=[], rc=1 ) base.fill_sack(load_system_repo='auto') except dnf.exceptions.RepoError as e: self.module.fail_json( msg="{0}".format(to_text(e)), results=[], rc=1 ) if self.bugfix: key = {'advisory_type__eq': 'bugfix'} base._update_security_filters = [base.sack.query().filter(**key)] if self.security: key = {'advisory_type__eq': 'security'} base._update_security_filters = [base.sack.query().filter(**key)] return base def list_items(self, command): """List package info based on the command.""" # Rename updates to upgrades if command == 'updates': command = 'upgrades' # Return the corresponding packages if command in ['installed', 'upgrades', 'available']: results = [ self._package_dict(package) for package in getattr(self.base.sack.query(), command)()] # Return the enabled repository ids elif command in ['repos', 'repositories']: results = [ {'repoid': repo.id, 'state': 'enabled'} for repo in self.base.repos.iter_enabled()] # Return any matching packages else: packages = dnf.subject.Subject(command).get_best_query(self.base.sack) results = [self._package_dict(package) for package in packages] self.module.exit_json(msg="", results=results) def _is_installed(self, pkg): installed = self.base.sack.query().installed() if installed.filter(name=pkg): return True else: return False def _is_newer_version_installed(self, pkg_name): candidate_pkg = self._packagename_dict(pkg_name) if not candidate_pkg: # The user didn't provide a versioned rpm, so version checking is # not required return False installed = self.base.sack.query().installed() installed_pkg = installed.filter(name=candidate_pkg['name']).run() if installed_pkg: installed_pkg = installed_pkg[0] # this looks weird but one is a dict and the other is a dnf.Package evr_cmp = self._compare_evr( installed_pkg.epoch, installed_pkg.version, installed_pkg.release, candidate_pkg['epoch'], candidate_pkg['version'], candidate_pkg['release'], ) if evr_cmp == 1: return True else: return False else: return False def _mark_package_install(self, pkg_spec, upgrade=False): """Mark the package for install.""" is_newer_version_installed = self._is_newer_version_installed(pkg_spec) is_installed = self._is_installed(pkg_spec) try: if self.allow_downgrade: # dnf only does allow_downgrade, we have to handle this ourselves # because it allows a possibility for non-idempotent transactions # on a system's package set (pending the yum repo has many old # NVRs indexed) if upgrade: if is_installed: self.base.upgrade(pkg_spec) else: self.base.install(pkg_spec) else: self.base.install(pkg_spec) elif not self.allow_downgrade and is_newer_version_installed: return {'failed': False, 'msg': '', 'failure': '', 'rc': 0} elif not is_newer_version_installed: if upgrade: if is_installed: self.base.upgrade(pkg_spec) else: self.base.install(pkg_spec) else: self.base.install(pkg_spec) else: if upgrade: if is_installed: self.base.upgrade(pkg_spec) else: self.base.install(pkg_spec) else: self.base.install(pkg_spec) return {'failed': False, 'msg': 'Installed: {0}'.format(pkg_spec), 'failure': '', 'rc': 0} except dnf.exceptions.MarkingError as e: return { 'failed': True, 'msg': "No package {0} available.".format(pkg_spec), 'failure': " ".join((pkg_spec, to_native(e))), 'rc': 1, "results": [] } except dnf.exceptions.DepsolveError as e: return { 'failed': True, 'msg': "Depsolve Error occured for package {0}.".format(pkg_spec), 'failure': " ".join((pkg_spec, to_native(e))), 'rc': 1, "results": [] } except dnf.exceptions.Error as e: if to_text("already installed") in to_text(e): return {'failed': False, 'msg': '', 'failure': ''} else: return { 'failed': True, 'msg': "Unknown Error occured for package {0}.".format(pkg_spec), 'failure': " ".join((pkg_spec, to_native(e))), 'rc': 1, "results": [] } def _whatprovides(self, filepath): available = self.base.sack.query().available() pkg_spec = available.filter(provides=filepath).run() if pkg_spec: return pkg_spec[0].name def _parse_spec_group_file(self): pkg_specs, grp_specs, module_specs, filenames = [], [], [], [] already_loaded_comps = False # Only load this if necessary, it's slow for name in self.names: if '://' in name: name = self.fetch_rpm_from_url(name) filenames.append(name) elif name.endswith(".rpm"): filenames.append(name) elif name.startswith("@") or ('/' in name): # like "dnf install /usr/bin/vi" if '/' in name: pkg_spec = self._whatprovides(name) if pkg_spec: pkg_specs.append(pkg_spec) continue if not already_loaded_comps: self.base.read_comps() already_loaded_comps = True grp_env_mdl_candidate = name[1:].strip() if self.with_modules: mdl = self.module_base._get_modules(grp_env_mdl_candidate) if mdl[0]: module_specs.append(grp_env_mdl_candidate) else: grp_specs.append(grp_env_mdl_candidate) else: grp_specs.append(grp_env_mdl_candidate) else: pkg_specs.append(name) return pkg_specs, grp_specs, module_specs, filenames def _update_only(self, pkgs): not_installed = [] for pkg in pkgs: if self._is_installed(pkg): try: if isinstance(to_text(pkg), text_type): self.base.upgrade(pkg) else: self.base.package_upgrade(pkg) except Exception as e: self.module.fail_json( msg="Error occured attempting update_only operation: {0}".format(to_native(e)), results=[], rc=1, ) else: not_installed.append(pkg) return not_installed def _install_remote_rpms(self, filenames): if int(dnf.__version__.split(".")[0]) >= 2: pkgs = list(sorted(self.base.add_remote_rpms(list(filenames)), reverse=True)) else: pkgs = [] try: for filename in filenames: pkgs.append(self.base.add_remote_rpm(filename)) except IOError as e: if to_text("Can not load RPM file") in to_text(e): self.module.fail_json( msg="Error occured attempting remote rpm install of package: {0}. {1}".format(filename, to_native(e)), results=[], rc=1, ) if self.update_only: self._update_only(pkgs) else: for pkg in pkgs: try: if self._is_newer_version_installed(self._package_dict(pkg)['nevra']): if self.allow_downgrade: self.base.package_install(pkg) else: self.base.package_install(pkg) except Exception as e: self.module.fail_json( msg="Error occured attempting remote rpm operation: {0}".format(to_native(e)), results=[], rc=1, ) def _is_module_installed(self, module_spec): if self.with_modules: module_spec = module_spec.strip() module_list, nsv = self.module_base._get_modules(module_spec) if nsv.stream in self.base._moduleContainer.getEnabledStream(nsv.name): return True return False # seems like a sane default def ensure(self): allow_erasing = False response = { 'msg': "", 'changed': False, 'results': [], 'rc': 0 } # Accumulate failures. Package management modules install what they can # and fail with a message about what they can't. failure_response = { 'msg': "", 'failures': [], 'results': [], 'rc': 1 } # Autoremove is called alone # Jump to remove path where base.autoremove() is run if not self.names and self.autoremove: self.names = [] self.state = 'absent' if self.names == ['*'] and self.state == 'latest': try: self.base.upgrade_all() except dnf.exceptions.DepsolveError as e: failure_response['msg'] = "Depsolve Error occured attempting to upgrade all packages" self.module.fail_json(**failure_response) else: pkg_specs, group_specs, module_specs, filenames = self._parse_spec_group_file() pkg_specs = [p.strip() for p in pkg_specs] filenames = [f.strip() for f in filenames] groups = [] environments = [] for group_spec in (g.strip() for g in group_specs): group = self.base.comps.group_by_pattern(group_spec) if group: groups.append(group.id) else: environment = self.base.comps.environment_by_pattern(group_spec) if environment: environments.append(environment.id) else: self.module.fail_json( msg="No group {0} available.".format(group_spec), results=[], ) if self.state in ['installed', 'present']: # Install files. self._install_remote_rpms(filenames) for filename in filenames: response['results'].append("Installed {0}".format(filename)) # Install modules if module_specs and self.with_modules: for module in module_specs: try: if not self._is_module_installed(module): response['results'].append("Module {0} installed.".format(module)) self.module_base.install([module]) self.module_base.enable([module]) except dnf.exceptions.MarkingErrors as e: failure_response['failures'].append(' '.join((module, to_native(e)))) # Install groups. for group in groups: try: group_pkg_count_installed = self.base.group_install(group, dnf.const.GROUP_PACKAGE_TYPES) if group_pkg_count_installed == 0: response['results'].append("Group {0} already installed.".format(group)) else: response['results'].append("Group {0} installed.".format(group)) except dnf.exceptions.DepsolveError as e: failure_response['msg'] = "Depsolve Error occured attempting to install group: {0}".format(group) self.module.fail_json(**failure_response) except dnf.exceptions.Error as e: # In dnf 2.0 if all the mandatory packages in a group do # not install, an error is raised. We want to capture # this but still install as much as possible. failure_response['failures'].append(" ".join((group, to_native(e)))) for environment in environments: try: self.base.environment_install(environment, dnf.const.GROUP_PACKAGE_TYPES) except dnf.exceptions.DepsolveError as e: failure_response['msg'] = "Depsolve Error occured attempting to install environment: {0}".format(environment) self.module.fail_json(**failure_response) except dnf.exceptions.Error as e: failure_response['failures'].append(" ".join((environment, to_native(e)))) if module_specs and not self.with_modules: # This means that the group or env wasn't found in comps self.module.fail_json( msg="No group {0} available.".format(module_specs[0]), results=[], ) # Install packages. if self.update_only: not_installed = self._update_only(pkg_specs) for spec in not_installed: response['results'].append("Packages providing %s not installed due to update_only specified" % spec) else: for pkg_spec in pkg_specs: install_result = self._mark_package_install(pkg_spec) if install_result['failed']: failure_response['msg'] += install_result['msg'] failure_response['failures'].append(self._sanitize_dnf_error_msg_install(pkg_spec, install_result['failure'])) else: response['results'].append(install_result['msg']) elif self.state == 'latest': # "latest" is same as "installed" for filenames. self._install_remote_rpms(filenames) for filename in filenames: response['results'].append("Installed {0}".format(filename)) # Upgrade modules if module_specs and self.with_modules: for module in module_specs: try: if self._is_module_installed(module): response['results'].append("Module {0} upgraded.".format(module)) self.module_base.upgrade([module]) except dnf.exceptions.MarkingErrors as e: failure_response['failures'].append(' '.join((module, to_native(e)))) for group in groups: try: try: self.base.group_upgrade(group) response['results'].append("Group {0} upgraded.".format(group)) except dnf.exceptions.CompsError: if not self.update_only: # If not already installed, try to install. group_pkg_count_installed = self.base.group_install(group, dnf.const.GROUP_PACKAGE_TYPES) if group_pkg_count_installed == 0: response['results'].append("Group {0} already installed.".format(group)) else: response['results'].append("Group {0} installed.".format(group)) except dnf.exceptions.Error as e: failure_response['failures'].append(" ".join((group, to_native(e)))) for environment in environments: try: try: self.base.environment_upgrade(environment) except dnf.exceptions.CompsError: # If not already installed, try to install. self.base.environment_install(environment, dnf.const.GROUP_PACKAGE_TYPES) except dnf.exceptions.DepsolveError as e: failure_response['msg'] = "Depsolve Error occured attempting to install environment: {0}".format(environment) except dnf.exceptions.Error as e: failure_response['failures'].append(" ".join((environment, to_native(e)))) if self.update_only: not_installed = self._update_only(pkg_specs) for spec in not_installed: response['results'].append("Packages providing %s not installed due to update_only specified" % spec) else: for pkg_spec in pkg_specs: # best effort causes to install the latest package # even if not previously installed self.base.conf.best = True install_result = self._mark_package_install(pkg_spec, upgrade=True) if install_result['failed']: failure_response['msg'] += install_result['msg'] failure_response['failures'].append(self._sanitize_dnf_error_msg_install(pkg_spec, install_result['failure'])) else: response['results'].append(install_result['msg']) else: # state == absent if filenames: self.module.fail_json( msg="Cannot remove paths -- please specify package name.", results=[], ) # Remove modules if module_specs and self.with_modules: for module in module_specs: try: if self._is_module_installed(module): response['results'].append("Module {0} removed.".format(module)) self.module_base.remove([module]) self.module_base.disable([module]) self.module_base.reset([module]) except dnf.exceptions.MarkingErrors as e: failure_response['failures'].append(' '.join((module, to_native(e)))) for group in groups: try: self.base.group_remove(group) except dnf.exceptions.CompsError: # Group is already uninstalled. pass except AttributeError: # Group either isn't installed or wasn't marked installed at install time # because of DNF bug # # This is necessary until the upstream dnf API bug is fixed where installing # a group via the dnf API doesn't actually mark the group as installed # https://bugzilla.redhat.com/show_bug.cgi?id=1620324 pass for environment in environments: try: self.base.environment_remove(environment) except dnf.exceptions.CompsError: # Environment is already uninstalled. pass installed = self.base.sack.query().installed() for pkg_spec in pkg_specs: # short-circuit installed check for wildcard matching if '*' in pkg_spec: try: self.base.remove(pkg_spec) except dnf.exceptions.MarkingError as e: is_failure, handled_remove_error = self._sanitize_dnf_error_msg_remove(pkg_spec, to_native(e)) if is_failure: failure_response['failures'].append('{0} - {1}'.format(pkg_spec, to_native(e))) else: response['results'].append(handled_remove_error) continue installed_pkg = list(map(str, installed.filter(name=pkg_spec).run())) if installed_pkg: candidate_pkg = self._packagename_dict(installed_pkg[0]) installed_pkg = installed.filter(name=candidate_pkg['name']).run() else: candidate_pkg = self._packagename_dict(pkg_spec) installed_pkg = installed.filter(nevra=pkg_spec).run() if installed_pkg: installed_pkg = installed_pkg[0] evr_cmp = self._compare_evr( installed_pkg.epoch, installed_pkg.version, installed_pkg.release, candidate_pkg['epoch'], candidate_pkg['version'], candidate_pkg['release'], ) if evr_cmp == 0: self.base.remove(pkg_spec) # Like the dnf CLI we want to allow recursive removal of dependent # packages allow_erasing = True if self.autoremove: self.base.autoremove() try: if not self.base.resolve(allow_erasing=allow_erasing): if failure_response['failures']: failure_response['msg'] = 'Failed to install some of the specified packages' self.module.fail_json(**failure_response) response['msg'] = "Nothing to do" self.module.exit_json(**response) else: response['changed'] = True if failure_response['failures']: failure_response['msg'] = 'Failed to install some of the specified packages', self.module.fail_json(**failure_response) if self.module.check_mode: response['msg'] = "Check mode: No changes made, but would have if not in check mode" self.module.exit_json(**response) try: if self.download_only and self.download_dir and self.base.conf.destdir: dnf.util.ensure_dir(self.base.conf.destdir) self.base.repos.all().pkgdir = self.base.conf.destdir self.base.download_packages(self.base.transaction.install_set) except dnf.exceptions.DownloadError as e: self.module.fail_json( msg="Failed to download packages: {0}".format(to_text(e)), results=[], ) if self.download_only: for package in self.base.transaction.install_set: response['results'].append("Downloaded: {0}".format(package)) self.module.exit_json(**response) else: self.base.do_transaction() for package in self.base.transaction.install_set: response['results'].append("Installed: {0}".format(package)) for package in self.base.transaction.remove_set: response['results'].append("Removed: {0}".format(package)) if failure_response['failures']: failure_response['msg'] = 'Failed to install some of the specified packages', self.module.exit_json(**response) self.module.exit_json(**response) except dnf.exceptions.DepsolveError as e: failure_response['msg'] = "Depsolve Error occured: {0}".format(to_native(e)) self.module.fail_json(**failure_response) except dnf.exceptions.Error as e: if to_text("already installed") in to_text(e): response['changed'] = False response['results'].append("Package already installed: {0}".format(to_native(e))) self.module.exit_json(**response) else: failure_response['msg'] = "Unknown Error occured: {0}".format(to_native(e)) self.module.fail_json(**failure_response) @staticmethod def has_dnf(): return HAS_DNF def run(self): """The main function.""" # Check if autoremove is called correctly if self.autoremove: if LooseVersion(dnf.__version__) < LooseVersion('2.0.1'): self.module.fail_json( msg="Autoremove requires dnf>=2.0.1. Current dnf version is %s" % dnf.__version__, results=[], ) # Check if download_dir is called correctly if self.download_dir: if LooseVersion(dnf.__version__) < LooseVersion('2.6.2'): self.module.fail_json( msg="download_dir requires dnf>=2.6.2. Current dnf version is %s" % dnf.__version__, results=[], ) if self.update_cache and not self.names and not self.list: self.base = self._base( self.conf_file, self.disable_gpg_check, self.disablerepo, self.enablerepo, self.installroot ) self.module.exit_json( msg="Cache updated", changed=False, results=[], rc=0 ) # Set state as installed by default # This is not set in AnsibleModule() because the following shouldn't happen # - dnf: autoremove=yes state=installed if self.state is None: self.state = 'installed' if self.list: self.base = self._base( self.conf_file, self.disable_gpg_check, self.disablerepo, self.enablerepo, self.installroot ) self.list_items(self.list) else: # Note: base takes a long time to run so we want to check for failure # before running it. if not dnf.util.am_i_root(): self.module.fail_json( msg="This command has to be run under the root user.", results=[], ) self.base = self._base( self.conf_file, self.disable_gpg_check, self.disablerepo, self.enablerepo, self.installroot ) if self.with_modules: self.module_base = dnf.module.module_base.ModuleBase(self.base) self.ensure() def main(): # state=installed name=pkgspec # state=removed name=pkgspec # state=latest name=pkgspec # # informational commands: # list=installed # list=updates # list=available # list=repos # list=pkgspec module = AnsibleModule( **yumdnf_argument_spec ) module_implementation = DnfModule(module) try: module_implementation.run() except dnf.exceptions.RepoError as de: module.fail_json( msg="Failed to synchronize repodata: {0}".format(to_native(de)), rc=1, results=[], changed=False ) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,683
dnf module crashes when omitting a specific appstream version
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Reading the [dnf module documentation](https://docs.ansible.com/ansible/latest/modules/dnf_module.html), I should be able to install a yum module just specifing an appstream module name with a profile without the need to specify an appstream version. But if you omit the appstream version, the dnf ansible plugin crashes with a strack-trace ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME dnf ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible-playbook 2.8.6 config file = /home/ansible/.virtualenvs/ansb28/ansible.cfg configured module search path = [u'/home/ansible/ansb28/ansible/library'] ansible python module location = /home/ansible/.virtualenvs/ansb28/lib/python2.7/site-packages/ansible executable location = /home/ansible/.virtualenvs/ansb28/bin/ansible-playbook python version = 2.7.5 (default, Sep 15 2016, 22:37:39) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_NOCOWS(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = True DEFAULT_CALLBACK_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/lib/python2.7/site-packages/ara/plugins/callbacks'] DEFAULT_CALLBACK_WHITELIST(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'ara'] DEFAULT_INVENTORY_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/ansible/plugins/inventory'] DEFAULT_MODULE_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/ansb28/ansible/library'] DEFAULT_ROLES_PATH(env: ANSIBLE_ROLES_PATH) = [u'/home/ansible/infra/roles'] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> management host: CentOS 7 target host: CentOS 8 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Try to run the following task against a CentOS 8 host: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Install rhn-client and other required packages (EL8) dnf: name: "@satellite-5-client/common" state: present when: ansible_distribution_major_version == "8" ``` The task fails with the following stacktrace: ``` centos8 | FAILED! => { "changed": false, "module_stderr": "Shared connection to 10.4.2.130 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/usr/lib/python3.6/site-packages/dnf/plugin.py\", line 102, in _caller\r\n getattr(plugin, method)()\r\n File \"/usr/lib/python3.6/site-packages/dnf-plugins/spacewalk.py\", line 84, in config\r\n self.cli.demands.root_user = True\r\nAttributeError: 'NoneType' object has no attribute 'demands'\r\n\r\nTraceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 114, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 106, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 49, in invoke_module\r\n imp.load_module('__main__', mod, module, MOD_DESC)\r\n File \"/usr/lib64/python3.6/imp.py\", line 235, in load_module\r\n return load_source(name, filename, file)\r\n File \"/usr/lib64/python3.6/imp.py\", line 170, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 618, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1322, in <module>\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1311, in main\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1290, in run\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 957, in ensure\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 890, in _is_module_installed\r\nTypeError: 'in <string>' requires string as left operand, not NoneType\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The appstream module is installed using the default module version without the need to specify it. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The dnf module crashes <!--- Paste verbatim command output between quotes --> ```paste below ```
https://github.com/ansible/ansible/issues/63683
https://github.com/ansible/ansible/pull/63819
b96ae6ab676744264a3915d57fd2fb9454e57384
ed86907587140daa933d8db08c7dca473757a63a
2019-10-18T13:35:31Z
python
2019-10-24T04:57:31Z
test/integration/targets/dnf/tasks/modularity.yml
# FUTURE - look at including AppStream support in our local repo - name: Include distribution specific variables include_vars: "{{ ansible_facts.distribution }}.yml" - name: install "{{ astream_name }}" module dnf: name: "{{ astream_name }}" state: present register: dnf_result - name: verify installation of "{{ astream_name }}" module assert: that: - "not dnf_result.failed" - "dnf_result.changed" - name: install "{{ astream_name }}" module again dnf: name: "{{ astream_name }}" state: present register: dnf_result - name: verify installation of "{{ astream_name }}" module again assert: that: - "not dnf_result.failed" - "not dnf_result.changed" - name: uninstall "{{ astream_name }}" module dnf: name: "{{ astream_name }}" state: absent register: dnf_result - name: verify uninstallation of "{{ astream_name }}" module assert: that: - "not dnf_result.failed" - "dnf_result.changed" - name: uninstall "{{ astream_name }}" module again dnf: name: "{{ astream_name }}" state: absent register: dnf_result - name: verify uninstallation of "{{ astream_name }}" module again assert: that: - "not dnf_result.failed" - "not dnf_result.changed"
closed
ansible/ansible
https://github.com/ansible/ansible
63,683
dnf module crashes when omitting a specific appstream version
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Reading the [dnf module documentation](https://docs.ansible.com/ansible/latest/modules/dnf_module.html), I should be able to install a yum module just specifing an appstream module name with a profile without the need to specify an appstream version. But if you omit the appstream version, the dnf ansible plugin crashes with a strack-trace ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME dnf ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible-playbook 2.8.6 config file = /home/ansible/.virtualenvs/ansb28/ansible.cfg configured module search path = [u'/home/ansible/ansb28/ansible/library'] ansible python module location = /home/ansible/.virtualenvs/ansb28/lib/python2.7/site-packages/ansible executable location = /home/ansible/.virtualenvs/ansb28/bin/ansible-playbook python version = 2.7.5 (default, Sep 15 2016, 22:37:39) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_NOCOWS(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = True DEFAULT_CALLBACK_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/lib/python2.7/site-packages/ara/plugins/callbacks'] DEFAULT_CALLBACK_WHITELIST(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'ara'] DEFAULT_INVENTORY_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/ansible/plugins/inventory'] DEFAULT_MODULE_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/ansb28/ansible/library'] DEFAULT_ROLES_PATH(env: ANSIBLE_ROLES_PATH) = [u'/home/ansible/infra/roles'] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> management host: CentOS 7 target host: CentOS 8 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Try to run the following task against a CentOS 8 host: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Install rhn-client and other required packages (EL8) dnf: name: "@satellite-5-client/common" state: present when: ansible_distribution_major_version == "8" ``` The task fails with the following stacktrace: ``` centos8 | FAILED! => { "changed": false, "module_stderr": "Shared connection to 10.4.2.130 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/usr/lib/python3.6/site-packages/dnf/plugin.py\", line 102, in _caller\r\n getattr(plugin, method)()\r\n File \"/usr/lib/python3.6/site-packages/dnf-plugins/spacewalk.py\", line 84, in config\r\n self.cli.demands.root_user = True\r\nAttributeError: 'NoneType' object has no attribute 'demands'\r\n\r\nTraceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 114, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 106, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 49, in invoke_module\r\n imp.load_module('__main__', mod, module, MOD_DESC)\r\n File \"/usr/lib64/python3.6/imp.py\", line 235, in load_module\r\n return load_source(name, filename, file)\r\n File \"/usr/lib64/python3.6/imp.py\", line 170, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 618, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1322, in <module>\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1311, in main\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1290, in run\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 957, in ensure\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 890, in _is_module_installed\r\nTypeError: 'in <string>' requires string as left operand, not NoneType\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The appstream module is installed using the default module version without the need to specify it. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The dnf module crashes <!--- Paste verbatim command output between quotes --> ```paste below ```
https://github.com/ansible/ansible/issues/63683
https://github.com/ansible/ansible/pull/63819
b96ae6ab676744264a3915d57fd2fb9454e57384
ed86907587140daa933d8db08c7dca473757a63a
2019-10-18T13:35:31Z
python
2019-10-24T04:57:31Z
test/integration/targets/dnf/vars/Fedora.yml
astream_name: '@ripgrep:master/default'
closed
ansible/ansible
https://github.com/ansible/ansible
63,683
dnf module crashes when omitting a specific appstream version
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Reading the [dnf module documentation](https://docs.ansible.com/ansible/latest/modules/dnf_module.html), I should be able to install a yum module just specifing an appstream module name with a profile without the need to specify an appstream version. But if you omit the appstream version, the dnf ansible plugin crashes with a strack-trace ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME dnf ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible-playbook 2.8.6 config file = /home/ansible/.virtualenvs/ansb28/ansible.cfg configured module search path = [u'/home/ansible/ansb28/ansible/library'] ansible python module location = /home/ansible/.virtualenvs/ansb28/lib/python2.7/site-packages/ansible executable location = /home/ansible/.virtualenvs/ansb28/bin/ansible-playbook python version = 2.7.5 (default, Sep 15 2016, 22:37:39) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_NOCOWS(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = True DEFAULT_CALLBACK_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/lib/python2.7/site-packages/ara/plugins/callbacks'] DEFAULT_CALLBACK_WHITELIST(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'ara'] DEFAULT_INVENTORY_PLUGIN_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/.virtualenvs/ansb28/ansible/plugins/inventory'] DEFAULT_MODULE_PATH(/home/ansible/.virtualenvs/ansb28/ansible.cfg) = [u'/home/ansibleiso/ansb28/ansible/library'] DEFAULT_ROLES_PATH(env: ANSIBLE_ROLES_PATH) = [u'/home/ansible/infra/roles'] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> management host: CentOS 7 target host: CentOS 8 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Try to run the following task against a CentOS 8 host: <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Install rhn-client and other required packages (EL8) dnf: name: "@satellite-5-client/common" state: present when: ansible_distribution_major_version == "8" ``` The task fails with the following stacktrace: ``` centos8 | FAILED! => { "changed": false, "module_stderr": "Shared connection to 10.4.2.130 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/usr/lib/python3.6/site-packages/dnf/plugin.py\", line 102, in _caller\r\n getattr(plugin, method)()\r\n File \"/usr/lib/python3.6/site-packages/dnf-plugins/spacewalk.py\", line 84, in config\r\n self.cli.demands.root_user = True\r\nAttributeError: 'NoneType' object has no attribute 'demands'\r\n\r\nTraceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 114, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 106, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 49, in invoke_module\r\n imp.load_module('__main__', mod, module, MOD_DESC)\r\n File \"/usr/lib64/python3.6/imp.py\", line 235, in load_module\r\n return load_source(name, filename, file)\r\n File \"/usr/lib64/python3.6/imp.py\", line 170, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 618, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1322, in <module>\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1311, in main\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1290, in run\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 957, in ensure\r\n File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 890, in _is_module_installed\r\nTypeError: 'in <string>' requires string as left operand, not NoneType\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The appstream module is installed using the default module version without the need to specify it. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The dnf module crashes <!--- Paste verbatim command output between quotes --> ```paste below ```
https://github.com/ansible/ansible/issues/63683
https://github.com/ansible/ansible/pull/63819
b96ae6ab676744264a3915d57fd2fb9454e57384
ed86907587140daa933d8db08c7dca473757a63a
2019-10-18T13:35:31Z
python
2019-10-24T04:57:31Z
test/integration/targets/dnf/vars/RedHat.yml
astream_name: '@php:7.2/minimal'
closed
ansible/ansible
https://github.com/ansible/ansible
63,490
Append user to group fails with FileNotFoundError
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Append user to group fails with `FileNotFoundError` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME user ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/ubuntu/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] ``` ##### CONFIGURATION ```paste below ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True ``` `pipelining = False` gives the same error. ##### OS / ENVIRONMENT * Source OS: Ubuntu 18.04 (installed from http://ppa.launchpad.net/ansible/ansible/ubuntu) * Target OS: Alpine Linux 3.10.2 * Target Python: Python 3.7.3 User is not part of the `wheel` group. ```sh # id nv uid=1000(nv) gid=1000(nv) groups=1000(nv) ``` ##### STEPS TO REPRODUCE ```sh ansible myhost -vvv -m user -a "name=nv groups=wheel append=yes" -e ansible_python_interpreter=/usr/bin/python3 -i hosts.yml -u root ``` ##### EXPECTED RESULTS user `nv` added to group `wheel`. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below ansible 2.8.5 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/ubuntu/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] Using /etc/ansible/ansible.cfg as config file host_list declined parsing /home/ubuntu/ansible-labs/ansible/hosts.yml as it did not pass it's verify_file() method script declined parsing /home/ubuntu/ansible-labs/ansible/hosts.yml as it did not pass it's verify_file() method Parsed /home/ubuntu/ansible-labs/ansible/hosts.yml inventory source with yaml plugin META: ran handlers Using module file /usr/lib/python2.7/dist-packages/ansible/modules/system/user.py Pipelining is enabled. <myhost> ESTABLISH SSH CONNECTION FOR USER: root <myhost> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="root"' -o ConnectTimeout=10 -o ControlPath=/home/ubuntu/.ansible/cp/a1dce85073 myhost '/bin/sh -c '"'"'/usr/bin/python3 && sleep 0'"'"'' <myhost> (1, '', '<stdin>:18: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module\'s documentation for alternative uses\nTraceback (most recent call last):\n File "<stdin>", line 114, in <module>\n File "<stdin>", line 106, in _ansiballz_main\n File "<stdin>", line 49, in invoke_module\n File "/usr/lib/python3.7/imp.py", line 234, in load_module\n return load_source(name, filename, file)\n File "/usr/lib/python3.7/imp.py", line 169, in load_source\n module = _exec(spec, sys.modules[name])\n File "<frozen importlib._bootstrap>", line 630, in _exec\n File "<frozen importlib._bootstrap_external>", line 728, in exec_module\n File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2962, in <module>\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2901, in main\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2770, in modify_user\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 824, in get_groups_set\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 891, in user_info\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 899, in user_password\nFileNotFoundError: [Errno 2] No such file or directory\n') <myhost> Failed to connect to the host via ssh: <stdin>:18: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses Traceback (most recent call last): File "<stdin>", line 114, in <module> File "<stdin>", line 106, in _ansiballz_main File "<stdin>", line 49, in invoke_module File "/usr/lib/python3.7/imp.py", line 234, in load_module return load_source(name, filename, file) File "/usr/lib/python3.7/imp.py", line 169, in load_source module = _exec(spec, sys.modules[name]) File "<frozen importlib._bootstrap>", line 630, in _exec File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2962, in <module> File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2901, in main File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2770, in modify_user File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 824, in get_groups_set File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 891, in user_info File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 899, in user_password FileNotFoundError: [Errno 2] No such file or directory myhost | FAILED! => { "changed": false, "module_stderr": "<stdin>:18: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses\nTraceback (most recent call last):\n File \"<stdin>\", line 114, in <module>\n File \"<stdin>\", line 106, in _ansiballz_main\n File \"<stdin>\", line 49, in invoke_module\n File \"/usr/lib/python3.7/imp.py\", line 234, in load_module\n return load_source(name, filename, file)\n File \"/usr/lib/python3.7/imp.py\", line 169, in load_source\n module = _exec(spec, sys.modules[name])\n File \"<frozen importlib._bootstrap>\", line 630, in _exec\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 2962, in <module>\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 2901, in main\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 2770, in modify_user\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 824, in get_groups_set\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 891, in user_info\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 899, in user_password\nFileNotFoundError: [Errno 2] No such file or directory\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
https://github.com/ansible/ansible/issues/63490
https://github.com/ansible/ansible/pull/63888
7f5d1ab2b730f1a2cbe7b4d578ec72a49636a282
af0d70cb6fbb559f601aac076fe11a82b78709c5
2019-10-15T03:40:16Z
python
2019-10-24T19:22:41Z
changelogs/fragments/user_missing_etc_shadow.yml
closed
ansible/ansible
https://github.com/ansible/ansible
63,490
Append user to group fails with FileNotFoundError
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Append user to group fails with `FileNotFoundError` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME user ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/ubuntu/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] ``` ##### CONFIGURATION ```paste below ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True ``` `pipelining = False` gives the same error. ##### OS / ENVIRONMENT * Source OS: Ubuntu 18.04 (installed from http://ppa.launchpad.net/ansible/ansible/ubuntu) * Target OS: Alpine Linux 3.10.2 * Target Python: Python 3.7.3 User is not part of the `wheel` group. ```sh # id nv uid=1000(nv) gid=1000(nv) groups=1000(nv) ``` ##### STEPS TO REPRODUCE ```sh ansible myhost -vvv -m user -a "name=nv groups=wheel append=yes" -e ansible_python_interpreter=/usr/bin/python3 -i hosts.yml -u root ``` ##### EXPECTED RESULTS user `nv` added to group `wheel`. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below ansible 2.8.5 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/ubuntu/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0] Using /etc/ansible/ansible.cfg as config file host_list declined parsing /home/ubuntu/ansible-labs/ansible/hosts.yml as it did not pass it's verify_file() method script declined parsing /home/ubuntu/ansible-labs/ansible/hosts.yml as it did not pass it's verify_file() method Parsed /home/ubuntu/ansible-labs/ansible/hosts.yml inventory source with yaml plugin META: ran handlers Using module file /usr/lib/python2.7/dist-packages/ansible/modules/system/user.py Pipelining is enabled. <myhost> ESTABLISH SSH CONNECTION FOR USER: root <myhost> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="root"' -o ConnectTimeout=10 -o ControlPath=/home/ubuntu/.ansible/cp/a1dce85073 myhost '/bin/sh -c '"'"'/usr/bin/python3 && sleep 0'"'"'' <myhost> (1, '', '<stdin>:18: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module\'s documentation for alternative uses\nTraceback (most recent call last):\n File "<stdin>", line 114, in <module>\n File "<stdin>", line 106, in _ansiballz_main\n File "<stdin>", line 49, in invoke_module\n File "/usr/lib/python3.7/imp.py", line 234, in load_module\n return load_source(name, filename, file)\n File "/usr/lib/python3.7/imp.py", line 169, in load_source\n module = _exec(spec, sys.modules[name])\n File "<frozen importlib._bootstrap>", line 630, in _exec\n File "<frozen importlib._bootstrap_external>", line 728, in exec_module\n File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2962, in <module>\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2901, in main\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2770, in modify_user\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 824, in get_groups_set\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 891, in user_info\n File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 899, in user_password\nFileNotFoundError: [Errno 2] No such file or directory\n') <myhost> Failed to connect to the host via ssh: <stdin>:18: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses Traceback (most recent call last): File "<stdin>", line 114, in <module> File "<stdin>", line 106, in _ansiballz_main File "<stdin>", line 49, in invoke_module File "/usr/lib/python3.7/imp.py", line 234, in load_module return load_source(name, filename, file) File "/usr/lib/python3.7/imp.py", line 169, in load_source module = _exec(spec, sys.modules[name]) File "<frozen importlib._bootstrap>", line 630, in _exec File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2962, in <module> File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2901, in main File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 2770, in modify_user File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 824, in get_groups_set File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 891, in user_info File "/tmp/ansible_user_payload_8xr4egvj/__main__.py", line 899, in user_password FileNotFoundError: [Errno 2] No such file or directory myhost | FAILED! => { "changed": false, "module_stderr": "<stdin>:18: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses\nTraceback (most recent call last):\n File \"<stdin>\", line 114, in <module>\n File \"<stdin>\", line 106, in _ansiballz_main\n File \"<stdin>\", line 49, in invoke_module\n File \"/usr/lib/python3.7/imp.py\", line 234, in load_module\n return load_source(name, filename, file)\n File \"/usr/lib/python3.7/imp.py\", line 169, in load_source\n module = _exec(spec, sys.modules[name])\n File \"<frozen importlib._bootstrap>\", line 630, in _exec\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 2962, in <module>\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 2901, in main\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 2770, in modify_user\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 824, in get_groups_set\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 891, in user_info\n File \"/tmp/ansible_user_payload_8xr4egvj/__main__.py\", line 899, in user_password\nFileNotFoundError: [Errno 2] No such file or directory\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
https://github.com/ansible/ansible/issues/63490
https://github.com/ansible/ansible/pull/63888
7f5d1ab2b730f1a2cbe7b4d578ec72a49636a282
af0d70cb6fbb559f601aac076fe11a82b78709c5
2019-10-15T03:40:16Z
python
2019-10-24T19:22:41Z
lib/ansible/modules/system/user.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Stephen Fromm <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = r''' module: user version_added: "0.2" short_description: Manage user accounts description: - Manage user accounts and user attributes. - For Windows targets, use the M(win_user) module instead. options: name: description: - Name of the user to create, remove or modify. type: str required: true aliases: [ user ] uid: description: - Optionally sets the I(UID) of the user. type: int comment: description: - Optionally sets the description (aka I(GECOS)) of user account. type: str hidden: description: - macOS only, optionally hide the user from the login window and system preferences. - The default will be C(yes) if the I(system) option is used. type: bool version_added: "2.6" non_unique: description: - Optionally when used with the -u option, this option allows to change the user ID to a non-unique value. type: bool default: no version_added: "1.1" seuser: description: - Optionally sets the seuser type (user_u) on selinux enabled systems. type: str version_added: "2.1" group: description: - Optionally sets the user's primary group (takes a group name). type: str groups: description: - List of groups user will be added to. When set to an empty string C(''), the user is removed from all groups except the primary group. - Before Ansible 2.3, the only input format allowed was a comma separated string. - Mutually exclusive with C(local) type: list append: description: - If C(yes), add the user to the groups specified in C(groups). - If C(no), user will only be added to the groups specified in C(groups), removing them from all other groups. - Mutually exclusive with C(local) type: bool default: no shell: description: - Optionally set the user's shell. - On macOS, before Ansible 2.5, the default shell for non-system users was C(/usr/bin/false). Since Ansible 2.5, the default shell for non-system users on macOS is C(/bin/bash). - On other operating systems, the default shell is determined by the underlying tool being used. See Notes for details. type: str home: description: - Optionally set the user's home directory. type: path skeleton: description: - Optionally set a home skeleton directory. - Requires C(create_home) option! type: str version_added: "2.0" password: description: - Optionally set the user's password to this crypted value. - On macOS systems, this value has to be cleartext. Beware of security issues. - To create a disabled account on Linux systems, set this to C('!') or C('*'). - To create a disabled account on OpenBSD, set this to C('*************'). - See U(https://docs.ansible.com/ansible/faq.html#how-do-i-generate-encrypted-passwords-for-the-user-module) for details on various ways to generate these password values. type: str state: description: - Whether the account should exist or not, taking action if the state is different from what is stated. type: str choices: [ absent, present ] default: present create_home: description: - Unless set to C(no), a home directory will be made for the user when the account is created or if the home directory does not exist. - Changed from C(createhome) to C(create_home) in Ansible 2.5. type: bool default: yes aliases: [ createhome ] move_home: description: - "If set to C(yes) when used with C(home: ), attempt to move the user's old home directory to the specified directory if it isn't there already and the old home exists." type: bool default: no system: description: - When creating an account C(state=present), setting this to C(yes) makes the user a system account. - This setting cannot be changed on existing users. type: bool default: no force: description: - This only affects C(state=absent), it forces removal of the user and associated directories on supported platforms. - The behavior is the same as C(userdel --force), check the man page for C(userdel) on your system for details and support. - When used with C(generate_ssh_key=yes) this forces an existing key to be overwritten. type: bool default: no remove: description: - This only affects C(state=absent), it attempts to remove directories associated with the user. - The behavior is the same as C(userdel --remove), check the man page for details and support. type: bool default: no login_class: description: - Optionally sets the user's login class, a feature of most BSD OSs. type: str generate_ssh_key: description: - Whether to generate a SSH key for the user in question. - This will B(not) overwrite an existing SSH key unless used with C(force=yes). type: bool default: no version_added: "0.9" ssh_key_bits: description: - Optionally specify number of bits in SSH key to create. type: int default: default set by ssh-keygen version_added: "0.9" ssh_key_type: description: - Optionally specify the type of SSH key to generate. - Available SSH key types will depend on implementation present on target host. type: str default: rsa version_added: "0.9" ssh_key_file: description: - Optionally specify the SSH key filename. - If this is a relative filename then it will be relative to the user's home directory. - This parameter defaults to I(.ssh/id_rsa). type: path version_added: "0.9" ssh_key_comment: description: - Optionally define the comment for the SSH key. type: str default: ansible-generated on $HOSTNAME version_added: "0.9" ssh_key_passphrase: description: - Set a passphrase for the SSH key. - If no passphrase is provided, the SSH key will default to having no passphrase. type: str version_added: "0.9" update_password: description: - C(always) will update passwords if they differ. - C(on_create) will only set the password for newly created users. type: str choices: [ always, on_create ] default: always version_added: "1.3" expires: description: - An expiry time for the user in epoch, it will be ignored on platforms that do not support this. - Currently supported on GNU/Linux, FreeBSD, and DragonFlyBSD. - Since Ansible 2.6 you can remove the expiry time specify a negative value. Currently supported on GNU/Linux and FreeBSD. type: float version_added: "1.9" password_lock: description: - Lock the password (usermod -L, pw lock, usermod -C). - BUT implementation differs on different platforms, this option does not always mean the user cannot login via other methods. - This option does not disable the user, only lock the password. Do not change the password in the same task. - Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD, OpenBSD. type: bool version_added: "2.6" local: description: - Forces the use of "local" command alternatives on platforms that implement it. - This is useful in environments that use centralized authentification when you want to manipulate the local users (i.e. it uses C(luseradd) instead of C(useradd)). - This will check C(/etc/passwd) for an existing account before invoking commands. If the local account database exists somewhere other than C(/etc/passwd), this setting will not work properly. - This requires that the above commands as well as C(/etc/passwd) must exist on the target host, otherwise it will be a fatal error. - Mutually exclusive with C(groups) and C(append) type: bool default: no version_added: "2.4" profile: description: - Sets the profile of the user. - Does nothing when used with other platforms. - Can set multiple profiles using comma separation. - To delete all the profiles, use C(profile=''). - Currently supported on Illumos/Solaris. type: str version_added: "2.8" authorization: description: - Sets the authorization of the user. - Does nothing when used with other platforms. - Can set multiple authorizations using comma separation. - To delete all authorizations, use C(authorization=''). - Currently supported on Illumos/Solaris. type: str version_added: "2.8" role: description: - Sets the role of the user. - Does nothing when used with other platforms. - Can set multiple roles using comma separation. - To delete all roles, use C(role=''). - Currently supported on Illumos/Solaris. type: str version_added: "2.8" notes: - There are specific requirements per platform on user management utilities. However they generally come pre-installed with the system and Ansible will require they are present at runtime. If they are not, a descriptive error message will be shown. - On SunOS platforms, the shadow file is backed up automatically since this module edits it directly. On other platforms, the shadow file is backed up by the underlying tools used by this module. - On macOS, this module uses C(dscl) to create, modify, and delete accounts. C(dseditgroup) is used to modify group membership. Accounts are hidden from the login window by modifying C(/Library/Preferences/com.apple.loginwindow.plist). - On FreeBSD, this module uses C(pw useradd) and C(chpass) to create, C(pw usermod) and C(chpass) to modify, C(pw userdel) remove, C(pw lock) to lock, and C(pw unlock) to unlock accounts. - On all other platforms, this module uses C(useradd) to create, C(usermod) to modify, and C(userdel) to remove accounts. seealso: - module: authorized_key - module: group - module: win_user author: - Stephen Fromm (@sfromm) ''' EXAMPLES = r''' - name: Add the user 'johnd' with a specific uid and a primary group of 'admin' user: name: johnd comment: John Doe uid: 1040 group: admin - name: Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups user: name: james shell: /bin/bash groups: admins,developers append: yes - name: Remove the user 'johnd' user: name: johnd state: absent remove: yes - name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa user: name: jsmith generate_ssh_key: yes ssh_key_bits: 2048 ssh_key_file: .ssh/id_rsa - name: Added a consultant whose account you want to expire user: name: james18 shell: /bin/zsh groups: developers expires: 1422403387 - name: Starting at Ansible 2.6, modify user, remove expiry time user: name: james18 expires: -1 ''' RETURN = r''' append: description: Whether or not to append the user to groups returned: When state is 'present' and the user exists type: bool sample: True comment: description: Comment section from passwd file, usually the user name returned: When user exists type: str sample: Agent Smith create_home: description: Whether or not to create the home directory returned: When user does not exist and not check mode type: bool sample: True force: description: Whether or not a user account was forcibly deleted returned: When state is 'absent' and user exists type: bool sample: False group: description: Primary user group ID returned: When user exists type: int sample: 1001 groups: description: List of groups of which the user is a member returned: When C(groups) is not empty and C(state) is 'present' type: str sample: 'chrony,apache' home: description: "Path to user's home directory" returned: When C(state) is 'present' type: str sample: '/home/asmith' move_home: description: Whether or not to move an existing home directory returned: When C(state) is 'present' and user exists type: bool sample: False name: description: User account name returned: always type: str sample: asmith password: description: Masked value of the password returned: When C(state) is 'present' and C(password) is not empty type: str sample: 'NOT_LOGGING_PASSWORD' remove: description: Whether or not to remove the user account returned: When C(state) is 'absent' and user exists type: bool sample: True shell: description: User login shell returned: When C(state) is 'present' type: str sample: '/bin/bash' ssh_fingerprint: description: Fingerprint of generated SSH key returned: When C(generate_ssh_key) is C(True) type: str sample: '2048 SHA256:aYNHYcyVm87Igh0IMEDMbvW0QDlRQfE0aJugp684ko8 ansible-generated on host (RSA)' ssh_key_file: description: Path to generated SSH private key file returned: When C(generate_ssh_key) is C(True) type: str sample: /home/asmith/.ssh/id_rsa ssh_public_key: description: Generated SSH public key file returned: When C(generate_ssh_key) is C(True) type: str sample: > 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC95opt4SPEC06tOYsJQJIuN23BbLMGmYo8ysVZQc4h2DZE9ugbjWWGS1/pweUGjVstgzMkBEeBCByaEf/RJKNecKRPeGd2Bw9DCj/bn5Z6rGfNENKBmo 618mUJBvdlEgea96QGjOwSB7/gmonduC7gsWDMNcOdSE3wJMTim4lddiBx4RgC9yXsJ6Tkz9BHD73MXPpT5ETnse+A3fw3IGVSjaueVnlUyUmOBf7fzmZbhlFVXf2Zi2rFTXqvbdGHKkzpw1U8eB8xFPP7y d5u1u0e6Acju/8aZ/l17IDFiLke5IzlqIMRTEbDwLNeO84YQKWTm9fODHzhYe0yvxqLiK07 ansible-generated on host' stderr: description: Standard error from running commands returned: When stderr is returned by a command that is run type: str sample: Group wheels does not exist stdout: description: Standard output from running commands returned: When standard output is returned by the command that is run type: str sample: system: description: Whether or not the account is a system account returned: When C(system) is passed to the module and the account does not exist type: bool sample: True uid: description: User ID of the user account returned: When C(UID) is passed to the module type: int sample: 1044 ''' import errno import grp import calendar import os import re import pty import pwd import select import shutil import socket import subprocess import time from ansible.module_utils import distro from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try: import spwd HAVE_SPWD = True except ImportError: HAVE_SPWD = False _HASH_RE = re.compile(r'[^a-zA-Z0-9./=]') class User(object): """ This is a generic User manipulation class that is subclassed based on platform. A subclass may wish to override the following action methods:- - create_user() - remove_user() - modify_user() - ssh_key_gen() - ssh_key_fingerprint() - user_exists() All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distribution = None PASSWORDFILE = '/etc/passwd' SHADOWFILE = '/etc/shadow' SHADOWFILE_EXPIRE_INDEX = 7 LOGIN_DEFS = '/etc/login.defs' DATE_FORMAT = '%Y-%m-%d' def __new__(cls, *args, **kwargs): return load_platform_subclass(User, args, kwargs) def __init__(self, module): self.module = module self.state = module.params['state'] self.name = module.params['name'] self.uid = module.params['uid'] self.hidden = module.params['hidden'] self.non_unique = module.params['non_unique'] self.seuser = module.params['seuser'] self.group = module.params['group'] self.comment = module.params['comment'] self.shell = module.params['shell'] self.password = module.params['password'] self.force = module.params['force'] self.remove = module.params['remove'] self.create_home = module.params['create_home'] self.move_home = module.params['move_home'] self.skeleton = module.params['skeleton'] self.system = module.params['system'] self.login_class = module.params['login_class'] self.append = module.params['append'] self.sshkeygen = module.params['generate_ssh_key'] self.ssh_bits = module.params['ssh_key_bits'] self.ssh_type = module.params['ssh_key_type'] self.ssh_comment = module.params['ssh_key_comment'] self.ssh_passphrase = module.params['ssh_key_passphrase'] self.update_password = module.params['update_password'] self.home = module.params['home'] self.expires = None self.password_lock = module.params['password_lock'] self.groups = None self.local = module.params['local'] self.profile = module.params['profile'] self.authorization = module.params['authorization'] self.role = module.params['role'] if module.params['groups'] is not None: self.groups = ','.join(module.params['groups']) if module.params['expires'] is not None: try: self.expires = time.gmtime(module.params['expires']) except Exception as e: module.fail_json(msg="Invalid value for 'expires' %s: %s" % (self.expires, to_native(e))) if module.params['ssh_key_file'] is not None: self.ssh_file = module.params['ssh_key_file'] else: self.ssh_file = os.path.join('.ssh', 'id_%s' % self.ssh_type) def check_password_encrypted(self): # Darwin needs cleartext password, so skip validation if self.module.params['password'] and self.platform != 'Darwin': maybe_invalid = False # Allow setting certain passwords in order to disable the account if self.module.params['password'] in set(['*', '!', '*************']): maybe_invalid = False else: # : for delimiter, * for disable user, ! for lock user # these characters are invalid in the password if any(char in self.module.params['password'] for char in ':*!'): maybe_invalid = True if '$' not in self.module.params['password']: maybe_invalid = True else: fields = self.module.params['password'].split("$") if len(fields) >= 3: # contains character outside the crypto constraint if bool(_HASH_RE.search(fields[-1])): maybe_invalid = True # md5 if fields[1] == '1' and len(fields[-1]) != 22: maybe_invalid = True # sha256 if fields[1] == '5' and len(fields[-1]) != 43: maybe_invalid = True # sha512 if fields[1] == '6' and len(fields[-1]) != 86: maybe_invalid = True else: maybe_invalid = True if maybe_invalid: self.module.warn("The input password appears not to have been hashed. " "The 'password' argument must be encrypted for this module to work properly.") def execute_command(self, cmd, use_unsafe_shell=False, data=None, obey_checkmode=True): if self.module.check_mode and obey_checkmode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') else: # cast all args to strings ansible-modules-core/issues/4397 cmd = [str(x) for x in cmd] return self.module.run_command(cmd, use_unsafe_shell=use_unsafe_shell, data=data) def backup_shadow(self): if not self.module.check_mode and self.SHADOWFILE: return self.module.backup_local(self.SHADOWFILE) def remove_user_userdel(self): if self.local: command_name = 'luserdel' else: command_name = 'userdel' cmd = [self.module.get_bin_path(command_name, True)] if self.force: cmd.append('-f') if self.remove: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def create_user_useradd(self): if self.local: command_name = 'luseradd' else: command_name = 'useradd' cmd = [self.module.get_bin_path(command_name, True)] if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.seuser is not None: cmd.append('-Z') cmd.append(self.seuser) if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) cmd.append('-g') cmd.append(self.group) elif self.group_exists(self.name): # use the -N option (no user group) if a group already # exists with the same name as the user to prevent # errors from useradd trying to create a group when # USERGROUPS_ENAB is set in /etc/login.defs. if os.path.exists('/etc/redhat-release'): dist = distro.linux_distribution(full_distribution_name=False) major_release = int(dist[1].split('.')[0]) if major_release <= 5: cmd.append('-n') else: cmd.append('-N') elif os.path.exists('/etc/SuSE-release'): # -N did not exist in useradd before SLE 11 and did not # automatically create a group dist = distro.linux_distribution(full_distribution_name=False) major_release = int(dist[1].split('.')[0]) if major_release >= 12: cmd.append('-N') else: cmd.append('-N') if self.groups is not None and not self.local and len(self.groups): groups = self.get_groups_set() cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None: cmd.append('-c') cmd.append(self.comment) if self.home is not None: # If the specified path to the user home contains parent directories that # do not exist, first create the home directory since useradd cannot # create parent directories parent = os.path.dirname(self.home) if not os.path.isdir(parent): self.create_homedir(self.home) cmd.append('-d') cmd.append(self.home) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if self.expires is not None: cmd.append('-e') if self.expires < time.gmtime(0): cmd.append('') else: cmd.append(time.strftime(self.DATE_FORMAT, self.expires)) if self.password is not None: cmd.append('-p') cmd.append(self.password) if self.create_home: if not self.local: cmd.append('-m') if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) else: cmd.append('-M') if self.system: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def _check_usermod_append(self): # check if this version of usermod can append groups if self.local: command_name = 'lusermod' else: command_name = 'usermod' usermod_path = self.module.get_bin_path(command_name, True) # for some reason, usermod --help cannot be used by non root # on RH/Fedora, due to lack of execute bit for others if not os.access(usermod_path, os.X_OK): return False cmd = [usermod_path, '--help'] (rc, data1, data2) = self.execute_command(cmd, obey_checkmode=False) helpout = data1 + data2 # check if --append exists lines = to_native(helpout).split('\n') for line in lines: if line.strip().startswith('-a, --append'): return True return False def modify_user_usermod(self): if self.local: command_name = 'lusermod' else: command_name = 'usermod' cmd = [self.module.get_bin_path(command_name, True)] info = self.user_info() has_append = self._check_usermod_append() if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) ginfo = self.group_info(self.group) if info[3] != ginfo[2]: cmd.append('-g') cmd.append(self.group) if self.groups is not None: # get a list of all groups for the user, including the primary current_groups = self.user_group_membership(exclude_primary=False) groups_need_mod = False groups = [] if self.groups == '': if current_groups and not self.append: groups_need_mod = True else: groups = self.get_groups_set(remove_existing=False) group_diff = set(current_groups).symmetric_difference(groups) if group_diff: if self.append: for g in groups: if g in group_diff: if has_append: cmd.append('-a') groups_need_mod = True break else: groups_need_mod = True if groups_need_mod and not self.local: if self.append and not has_append: cmd.append('-A') cmd.append(','.join(group_diff)) else: cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None and info[4] != self.comment: cmd.append('-c') cmd.append(self.comment) if self.home is not None and info[5] != self.home: cmd.append('-d') cmd.append(self.home) if self.move_home: cmd.append('-m') if self.shell is not None and info[6] != self.shell: cmd.append('-s') cmd.append(self.shell) if self.expires is not None: current_expires = int(self.user_password()[1]) if self.expires < time.gmtime(0): if current_expires >= 0: cmd.append('-e') cmd.append('') else: # Convert days since Epoch to seconds since Epoch as struct_time current_expire_date = time.gmtime(current_expires * 86400) # Current expires is negative or we compare year, month, and day only if current_expires < 0 or current_expire_date[:3] != self.expires[:3]: cmd.append('-e') cmd.append(time.strftime(self.DATE_FORMAT, self.expires)) # Lock if no password or unlocked, unlock only if locked if self.password_lock and not info[1].startswith('!'): cmd.append('-L') elif self.password_lock is False and info[1].startswith('!'): # usermod will refuse to unlock a user with no password, module shows 'changed' regardless cmd.append('-U') if self.update_password == 'always' and self.password is not None and info[1] != self.password: cmd.append('-p') cmd.append(self.password) # skip if no changes to be made if len(cmd) == 1: return (None, '', '') cmd.append(self.name) return self.execute_command(cmd) def group_exists(self, group): try: # Try group as a gid first grp.getgrgid(int(group)) return True except (ValueError, KeyError): try: grp.getgrnam(group) return True except KeyError: return False def group_info(self, group): if not self.group_exists(group): return False try: # Try group as a gid first return list(grp.getgrgid(int(group))) except (ValueError, KeyError): return list(grp.getgrnam(group)) def get_groups_set(self, remove_existing=True): if self.groups is None: return None info = self.user_info() groups = set(x.strip() for x in self.groups.split(',') if x) for g in groups.copy(): if not self.group_exists(g): self.module.fail_json(msg="Group %s does not exist" % (g)) if info and remove_existing and self.group_info(g)[2] == info[3]: groups.remove(g) return groups def user_group_membership(self, exclude_primary=True): ''' Return a list of groups the user belongs to ''' groups = [] info = self.get_pwd_info() for group in grp.getgrall(): if self.name in group.gr_mem: # Exclude the user's primary group by default if not exclude_primary: groups.append(group[0]) else: if info[3] != group.gr_gid: groups.append(group[0]) return groups def user_exists(self): # The pwd module does not distinguish between local and directory accounts. # It's output cannot be used to determine whether or not an account exists locally. # It returns True if the account exists locally or in the directory, so instead # look in the local PASSWORD file for an existing account. if self.local: if not os.path.exists(self.PASSWORDFILE): self.module.fail_json(msg="'local: true' specified but unable to find local account file {0} to parse.".format(self.PASSWORDFILE)) exists = False name_test = '{0}:'.format(self.name) with open(self.PASSWORDFILE, 'rb') as f: reversed_lines = f.readlines()[::-1] for line in reversed_lines: if line.startswith(to_bytes(name_test)): exists = True break if not exists: self.module.warn( "'local: true' specified and user '{name}' was not found in {file}. " "The local user account may already exist if the local account database exists " "somewhere other than {file}.".format(file=self.PASSWORDFILE, name=self.name)) return exists else: try: if pwd.getpwnam(self.name): return True except KeyError: return False def get_pwd_info(self): if not self.user_exists(): return False return list(pwd.getpwnam(self.name)) def user_info(self): if not self.user_exists(): return False info = self.get_pwd_info() if len(info[1]) == 1 or len(info[1]) == 0: info[1] = self.user_password()[0] return info def user_password(self): passwd = '' expires = '' if HAVE_SPWD: try: passwd = spwd.getspnam(self.name)[1] expires = spwd.getspnam(self.name)[7] return passwd, expires except KeyError: return passwd, expires except OSError as e: # Python 3.6 raises PermissionError instead of KeyError # Due to absence of PermissionError in python2.7 need to check # errno if e.errno in (errno.EACCES, errno.EPERM): return passwd, expires raise if not self.user_exists(): return passwd, expires elif self.SHADOWFILE: passwd, expires = self.parse_shadow_file() return passwd, expires def parse_shadow_file(self): passwd = '' expires = '' if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK): with open(self.SHADOWFILE, 'r') as f: for line in f: if line.startswith('%s:' % self.name): passwd = line.split(':')[1] expires = line.split(':')[self.SHADOWFILE_EXPIRE_INDEX] or -1 return passwd, expires def get_ssh_key_path(self): info = self.user_info() if os.path.isabs(self.ssh_file): ssh_key_file = self.ssh_file else: if not os.path.exists(info[5]) and not self.module.check_mode: raise Exception('User %s home directory does not exist' % self.name) ssh_key_file = os.path.join(info[5], self.ssh_file) return ssh_key_file def ssh_key_gen(self): info = self.user_info() overwrite = None try: ssh_key_file = self.get_ssh_key_path() except Exception as e: return (1, '', to_native(e)) ssh_dir = os.path.dirname(ssh_key_file) if not os.path.exists(ssh_dir): if self.module.check_mode: return (0, '', '') try: os.mkdir(ssh_dir, int('0700', 8)) os.chown(ssh_dir, info[2], info[3]) except OSError as e: return (1, '', 'Failed to create %s: %s' % (ssh_dir, to_native(e))) if os.path.exists(ssh_key_file): if self.force: # ssh-keygen doesn't support overwriting the key interactively, so send 'y' to confirm overwrite = 'y' else: return (None, 'Key already exists, use "force: yes" to overwrite', '') cmd = [self.module.get_bin_path('ssh-keygen', True)] cmd.append('-t') cmd.append(self.ssh_type) if self.ssh_bits > 0: cmd.append('-b') cmd.append(self.ssh_bits) cmd.append('-C') cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) if self.ssh_passphrase is not None: if self.module.check_mode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') master_in_fd, slave_in_fd = pty.openpty() master_out_fd, slave_out_fd = pty.openpty() master_err_fd, slave_err_fd = pty.openpty() env = os.environ.copy() env['LC_ALL'] = 'C' try: p = subprocess.Popen([to_bytes(c) for c in cmd], stdin=slave_in_fd, stdout=slave_out_fd, stderr=slave_err_fd, preexec_fn=os.setsid, env=env) out_buffer = b'' err_buffer = b'' while p.poll() is None: r, w, e = select.select([master_out_fd, master_err_fd], [], [], 1) first_prompt = b'Enter passphrase (empty for no passphrase):' second_prompt = b'Enter same passphrase again' prompt = first_prompt for fd in r: if fd == master_out_fd: chunk = os.read(master_out_fd, 10240) out_buffer += chunk if prompt in out_buffer: os.write(master_in_fd, to_bytes(self.ssh_passphrase, errors='strict') + b'\r') prompt = second_prompt else: chunk = os.read(master_err_fd, 10240) err_buffer += chunk if prompt in err_buffer: os.write(master_in_fd, to_bytes(self.ssh_passphrase, errors='strict') + b'\r') prompt = second_prompt if b'Overwrite (y/n)?' in out_buffer or b'Overwrite (y/n)?' in err_buffer: # The key was created between us checking for existence and now return (None, 'Key already exists', '') rc = p.returncode out = to_native(out_buffer) err = to_native(err_buffer) except OSError as e: return (1, '', to_native(e)) else: cmd.append('-N') cmd.append('') (rc, out, err) = self.execute_command(cmd, data=overwrite) if rc == 0 and not self.module.check_mode: # If the keys were successfully created, we should be able # to tweak ownership. os.chown(ssh_key_file, info[2], info[3]) os.chown('%s.pub' % ssh_key_file, info[2], info[3]) return (rc, out, err) def ssh_key_fingerprint(self): ssh_key_file = self.get_ssh_key_path() if not os.path.exists(ssh_key_file): return (1, 'SSH Key file %s does not exist' % ssh_key_file, '') cmd = [self.module.get_bin_path('ssh-keygen', True)] cmd.append('-l') cmd.append('-f') cmd.append(ssh_key_file) return self.execute_command(cmd, obey_checkmode=False) def get_ssh_public_key(self): ssh_public_key_file = '%s.pub' % self.get_ssh_key_path() try: with open(ssh_public_key_file, 'r') as f: ssh_public_key = f.read().strip() except IOError: return None return ssh_public_key def create_user(self): # by default we use the create_user_useradd method return self.create_user_useradd() def remove_user(self): # by default we use the remove_user_userdel method return self.remove_user_userdel() def modify_user(self): # by default we use the modify_user_usermod method return self.modify_user_usermod() def create_homedir(self, path): if not os.path.exists(path): if self.skeleton is not None: skeleton = self.skeleton else: skeleton = '/etc/skel' if os.path.exists(skeleton): try: shutil.copytree(skeleton, path, symlinks=True) except OSError as e: self.module.exit_json(failed=True, msg="%s" % to_native(e)) else: try: os.makedirs(path) except OSError as e: self.module.exit_json(failed=True, msg="%s" % to_native(e)) # get umask from /etc/login.defs and set correct home mode if os.path.exists(self.LOGIN_DEFS): with open(self.LOGIN_DEFS, 'r') as f: for line in f: m = re.match(r'^UMASK\s+(\d+)$', line) if m: umask = int(m.group(1), 8) mode = 0o777 & ~umask try: os.chmod(path, mode) except OSError as e: self.module.exit_json(failed=True, msg="%s" % to_native(e)) def chown_homedir(self, uid, gid, path): try: os.chown(path, uid, gid) for root, dirs, files in os.walk(path): for d in dirs: os.chown(os.path.join(root, d), uid, gid) for f in files: os.chown(os.path.join(root, f), uid, gid) except OSError as e: self.module.exit_json(failed=True, msg="%s" % to_native(e)) # =========================================== class FreeBsdUser(User): """ This is a FreeBSD User manipulation class - it uses the pw command to manipulate the user database, followed by the chpass command to change the password. This overrides the following methods from the generic class:- - create_user() - remove_user() - modify_user() """ platform = 'FreeBSD' distribution = None SHADOWFILE = '/etc/master.passwd' SHADOWFILE_EXPIRE_INDEX = 6 DATE_FORMAT = '%d-%b-%Y' def remove_user(self): cmd = [ self.module.get_bin_path('pw', True), 'userdel', '-n', self.name ] if self.remove: cmd.append('-r') return self.execute_command(cmd) def create_user(self): cmd = [ self.module.get_bin_path('pw', True), 'useradd', '-n', self.name, ] if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.comment is not None: cmd.append('-c') cmd.append(self.comment) if self.home is not None: cmd.append('-d') cmd.append(self.home) if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) cmd.append('-g') cmd.append(self.group) if self.groups is not None: groups = self.get_groups_set() cmd.append('-G') cmd.append(','.join(groups)) if self.create_home: cmd.append('-m') if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if self.login_class is not None: cmd.append('-L') cmd.append(self.login_class) if self.expires is not None: cmd.append('-e') if self.expires < time.gmtime(0): cmd.append('0') else: cmd.append(str(calendar.timegm(self.expires))) # system cannot be handled currently - should we error if its requested? # create the user (rc, out, err) = self.execute_command(cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) # we have to set the password in a second command if self.password is not None: cmd = [ self.module.get_bin_path('chpass', True), '-p', self.password, self.name ] return self.execute_command(cmd) return (rc, out, err) def modify_user(self): cmd = [ self.module.get_bin_path('pw', True), 'usermod', '-n', self.name ] cmd_len = len(cmd) info = self.user_info() if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.comment is not None and info[4] != self.comment: cmd.append('-c') cmd.append(self.comment) if self.home is not None: if (info[5] != self.home and self.move_home) or (not os.path.exists(self.home) and self.create_home): cmd.append('-m') if info[5] != self.home: cmd.append('-d') cmd.append(self.home) if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) ginfo = self.group_info(self.group) if info[3] != ginfo[2]: cmd.append('-g') cmd.append(self.group) if self.shell is not None and info[6] != self.shell: cmd.append('-s') cmd.append(self.shell) if self.login_class is not None: # find current login class user_login_class = None if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK): with open(self.SHADOWFILE, 'r') as f: for line in f: if line.startswith('%s:' % self.name): user_login_class = line.split(':')[4] # act only if login_class change if self.login_class != user_login_class: cmd.append('-L') cmd.append(self.login_class) if self.groups is not None: current_groups = self.user_group_membership() groups = self.get_groups_set() group_diff = set(current_groups).symmetric_difference(groups) groups_need_mod = False if group_diff: if self.append: for g in groups: if g in group_diff: groups_need_mod = True break else: groups_need_mod = True if groups_need_mod: cmd.append('-G') new_groups = groups if self.append: new_groups = groups | set(current_groups) cmd.append(','.join(new_groups)) if self.expires is not None: current_expires = int(self.user_password()[1]) # If expiration is negative or zero and the current expiration is greater than zero, disable expiration. # In OpenBSD, setting expiration to zero disables expiration. It does not expire the account. if self.expires <= time.gmtime(0): if current_expires > 0: cmd.append('-e') cmd.append('0') else: # Convert days since Epoch to seconds since Epoch as struct_time current_expire_date = time.gmtime(current_expires) # Current expires is negative or we compare year, month, and day only if current_expires <= 0 or current_expire_date[:3] != self.expires[:3]: cmd.append('-e') cmd.append(str(calendar.timegm(self.expires))) # modify the user if cmd will do anything if cmd_len != len(cmd): (rc, out, err) = self.execute_command(cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) else: (rc, out, err) = (None, '', '') # we have to set the password in a second command if self.update_password == 'always' and self.password is not None and info[1] != self.password: cmd = [ self.module.get_bin_path('chpass', True), '-p', self.password, self.name ] return self.execute_command(cmd) # we have to lock/unlock the password in a distinct command if self.password_lock and not info[1].startswith('*LOCKED*'): cmd = [ self.module.get_bin_path('pw', True), 'lock', self.name ] if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) return self.execute_command(cmd) elif self.password_lock is False and info[1].startswith('*LOCKED*'): cmd = [ self.module.get_bin_path('pw', True), 'unlock', self.name ] if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) return self.execute_command(cmd) return (rc, out, err) class DragonFlyBsdUser(FreeBsdUser): """ This is a DragonFlyBSD User manipulation class - it inherits the FreeBsdUser class behaviors, such as using the pw command to manipulate the user database, followed by the chpass command to change the password. """ platform = 'DragonFly' class OpenBSDUser(User): """ This is a OpenBSD User manipulation class. Main differences are that OpenBSD:- - has no concept of "system" account. - has no force delete user This overrides the following methods from the generic class:- - create_user() - remove_user() - modify_user() """ platform = 'OpenBSD' distribution = None SHADOWFILE = '/etc/master.passwd' def create_user(self): cmd = [self.module.get_bin_path('useradd', True)] if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) cmd.append('-g') cmd.append(self.group) if self.groups is not None: groups = self.get_groups_set() cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None: cmd.append('-c') cmd.append(self.comment) if self.home is not None: cmd.append('-d') cmd.append(self.home) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if self.login_class is not None: cmd.append('-L') cmd.append(self.login_class) if self.password is not None and self.password != '*': cmd.append('-p') cmd.append(self.password) if self.create_home: cmd.append('-m') if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) cmd.append(self.name) return self.execute_command(cmd) def remove_user_userdel(self): cmd = [self.module.get_bin_path('userdel', True)] if self.remove: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def modify_user(self): cmd = [self.module.get_bin_path('usermod', True)] info = self.user_info() if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) ginfo = self.group_info(self.group) if info[3] != ginfo[2]: cmd.append('-g') cmd.append(self.group) if self.groups is not None: current_groups = self.user_group_membership() groups_need_mod = False groups_option = '-S' groups = [] if self.groups == '': if current_groups and not self.append: groups_need_mod = True else: groups = self.get_groups_set() group_diff = set(current_groups).symmetric_difference(groups) if group_diff: if self.append: for g in groups: if g in group_diff: groups_option = '-G' groups_need_mod = True break else: groups_need_mod = True if groups_need_mod: cmd.append(groups_option) cmd.append(','.join(groups)) if self.comment is not None and info[4] != self.comment: cmd.append('-c') cmd.append(self.comment) if self.home is not None and info[5] != self.home: if self.move_home: cmd.append('-m') cmd.append('-d') cmd.append(self.home) if self.shell is not None and info[6] != self.shell: cmd.append('-s') cmd.append(self.shell) if self.login_class is not None: # find current login class user_login_class = None userinfo_cmd = [self.module.get_bin_path('userinfo', True), self.name] (rc, out, err) = self.execute_command(userinfo_cmd, obey_checkmode=False) for line in out.splitlines(): tokens = line.split() if tokens[0] == 'class' and len(tokens) == 2: user_login_class = tokens[1] # act only if login_class change if self.login_class != user_login_class: cmd.append('-L') cmd.append(self.login_class) if self.password_lock and not info[1].startswith('*'): cmd.append('-Z') elif self.password_lock is False and info[1].startswith('*'): cmd.append('-U') if self.update_password == 'always' and self.password is not None \ and self.password != '*' and info[1] != self.password: cmd.append('-p') cmd.append(self.password) # skip if no changes to be made if len(cmd) == 1: return (None, '', '') cmd.append(self.name) return self.execute_command(cmd) class NetBSDUser(User): """ This is a NetBSD User manipulation class. Main differences are that NetBSD:- - has no concept of "system" account. - has no force delete user This overrides the following methods from the generic class:- - create_user() - remove_user() - modify_user() """ platform = 'NetBSD' distribution = None SHADOWFILE = '/etc/master.passwd' def create_user(self): cmd = [self.module.get_bin_path('useradd', True)] if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) cmd.append('-g') cmd.append(self.group) if self.groups is not None: groups = self.get_groups_set() if len(groups) > 16: self.module.fail_json(msg="Too many groups (%d) NetBSD allows for 16 max." % len(groups)) cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None: cmd.append('-c') cmd.append(self.comment) if self.home is not None: cmd.append('-d') cmd.append(self.home) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if self.login_class is not None: cmd.append('-L') cmd.append(self.login_class) if self.password is not None: cmd.append('-p') cmd.append(self.password) if self.create_home: cmd.append('-m') if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) cmd.append(self.name) return self.execute_command(cmd) def remove_user_userdel(self): cmd = [self.module.get_bin_path('userdel', True)] if self.remove: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def modify_user(self): cmd = [self.module.get_bin_path('usermod', True)] info = self.user_info() if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) ginfo = self.group_info(self.group) if info[3] != ginfo[2]: cmd.append('-g') cmd.append(self.group) if self.groups is not None: current_groups = self.user_group_membership() groups_need_mod = False groups = [] if self.groups == '': if current_groups and not self.append: groups_need_mod = True else: groups = self.get_groups_set() group_diff = set(current_groups).symmetric_difference(groups) if group_diff: if self.append: for g in groups: if g in group_diff: groups = set(current_groups).union(groups) groups_need_mod = True break else: groups_need_mod = True if groups_need_mod: if len(groups) > 16: self.module.fail_json(msg="Too many groups (%d) NetBSD allows for 16 max." % len(groups)) cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None and info[4] != self.comment: cmd.append('-c') cmd.append(self.comment) if self.home is not None and info[5] != self.home: if self.move_home: cmd.append('-m') cmd.append('-d') cmd.append(self.home) if self.shell is not None and info[6] != self.shell: cmd.append('-s') cmd.append(self.shell) if self.login_class is not None: cmd.append('-L') cmd.append(self.login_class) if self.update_password == 'always' and self.password is not None and info[1] != self.password: cmd.append('-p') cmd.append(self.password) if self.password_lock and not info[1].startswith('*LOCKED*'): cmd.append('-C yes') elif self.password_lock is False and info[1].startswith('*LOCKED*'): cmd.append('-C no') # skip if no changes to be made if len(cmd) == 1: return (None, '', '') cmd.append(self.name) return self.execute_command(cmd) class SunOS(User): """ This is a SunOS User manipulation class - The main difference between this class and the generic user class is that Solaris-type distros don't support the concept of a "system" account and we need to edit the /etc/shadow file manually to set a password. (Ugh) This overrides the following methods from the generic class:- - create_user() - remove_user() - modify_user() - user_info() """ platform = 'SunOS' distribution = None SHADOWFILE = '/etc/shadow' USER_ATTR = '/etc/user_attr' def get_password_defaults(self): # Read password aging defaults try: minweeks = '' maxweeks = '' warnweeks = '' with open("/etc/default/passwd", 'r') as f: for line in f: line = line.strip() if (line.startswith('#') or line == ''): continue m = re.match(r'^([^#]*)#(.*)$', line) if m: # The line contains a hash / comment line = m.group(1) key, value = line.split('=') if key == "MINWEEKS": minweeks = value.rstrip('\n') elif key == "MAXWEEKS": maxweeks = value.rstrip('\n') elif key == "WARNWEEKS": warnweeks = value.rstrip('\n') except Exception as err: self.module.fail_json(msg="failed to read /etc/default/passwd: %s" % to_native(err)) return (minweeks, maxweeks, warnweeks) def remove_user(self): cmd = [self.module.get_bin_path('userdel', True)] if self.remove: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def create_user(self): cmd = [self.module.get_bin_path('useradd', True)] if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) cmd.append('-g') cmd.append(self.group) if self.groups is not None: groups = self.get_groups_set() cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None: cmd.append('-c') cmd.append(self.comment) if self.home is not None: cmd.append('-d') cmd.append(self.home) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if self.create_home: cmd.append('-m') if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) if self.profile is not None: cmd.append('-P') cmd.append(self.profile) if self.authorization is not None: cmd.append('-A') cmd.append(self.authorization) if self.role is not None: cmd.append('-R') cmd.append(self.role) cmd.append(self.name) (rc, out, err) = self.execute_command(cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) if not self.module.check_mode: # we have to set the password by editing the /etc/shadow file if self.password is not None: self.backup_shadow() minweeks, maxweeks, warnweeks = self.get_password_defaults() try: lines = [] with open(self.SHADOWFILE, 'rb') as f: for line in f: line = to_native(line, errors='surrogate_or_strict') fields = line.strip().split(':') if not fields[0] == self.name: lines.append(line) continue fields[1] = self.password fields[2] = str(int(time.time() // 86400)) if minweeks: try: fields[3] = str(int(minweeks) * 7) except ValueError: # mirror solaris, which allows for any value in this field, and ignores anything that is not an int. pass if maxweeks: try: fields[4] = str(int(maxweeks) * 7) except ValueError: # mirror solaris, which allows for any value in this field, and ignores anything that is not an int. pass if warnweeks: try: fields[5] = str(int(warnweeks) * 7) except ValueError: # mirror solaris, which allows for any value in this field, and ignores anything that is not an int. pass line = ':'.join(fields) lines.append('%s\n' % line) with open(self.SHADOWFILE, 'w+') as f: f.writelines(lines) except Exception as err: self.module.fail_json(msg="failed to update users password: %s" % to_native(err)) return (rc, out, err) def modify_user_usermod(self): cmd = [self.module.get_bin_path('usermod', True)] cmd_len = len(cmd) info = self.user_info() if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) ginfo = self.group_info(self.group) if info[3] != ginfo[2]: cmd.append('-g') cmd.append(self.group) if self.groups is not None: current_groups = self.user_group_membership() groups = self.get_groups_set() group_diff = set(current_groups).symmetric_difference(groups) groups_need_mod = False if group_diff: if self.append: for g in groups: if g in group_diff: groups_need_mod = True break else: groups_need_mod = True if groups_need_mod: cmd.append('-G') new_groups = groups if self.append: new_groups.update(current_groups) cmd.append(','.join(new_groups)) if self.comment is not None and info[4] != self.comment: cmd.append('-c') cmd.append(self.comment) if self.home is not None and info[5] != self.home: if self.move_home: cmd.append('-m') cmd.append('-d') cmd.append(self.home) if self.shell is not None and info[6] != self.shell: cmd.append('-s') cmd.append(self.shell) if self.profile is not None and info[7] != self.profile: cmd.append('-P') cmd.append(self.profile) if self.authorization is not None and info[8] != self.authorization: cmd.append('-A') cmd.append(self.authorization) if self.role is not None and info[9] != self.role: cmd.append('-R') cmd.append(self.role) # modify the user if cmd will do anything if cmd_len != len(cmd): cmd.append(self.name) (rc, out, err) = self.execute_command(cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) else: (rc, out, err) = (None, '', '') # we have to set the password by editing the /etc/shadow file if self.update_password == 'always' and self.password is not None and info[1] != self.password: self.backup_shadow() (rc, out, err) = (0, '', '') if not self.module.check_mode: minweeks, maxweeks, warnweeks = self.get_password_defaults() try: lines = [] with open(self.SHADOWFILE, 'rb') as f: for line in f: line = to_native(line, errors='surrogate_or_strict') fields = line.strip().split(':') if not fields[0] == self.name: lines.append(line) continue fields[1] = self.password fields[2] = str(int(time.time() // 86400)) if minweeks: fields[3] = str(int(minweeks) * 7) if maxweeks: fields[4] = str(int(maxweeks) * 7) if warnweeks: fields[5] = str(int(warnweeks) * 7) line = ':'.join(fields) lines.append('%s\n' % line) with open(self.SHADOWFILE, 'w+') as f: f.writelines(lines) rc = 0 except Exception as err: self.module.fail_json(msg="failed to update users password: %s" % to_native(err)) return (rc, out, err) def user_info(self): info = super(SunOS, self).user_info() if info: info += self._user_attr_info() return info def _user_attr_info(self): info = [''] * 3 with open(self.USER_ATTR, 'r') as file_handler: for line in file_handler: lines = line.strip().split('::::') if lines[0] == self.name: tmp = dict(x.split('=') for x in lines[1].split(';')) info[0] = tmp.get('profiles', '') info[1] = tmp.get('auths', '') info[2] = tmp.get('roles', '') return info class DarwinUser(User): """ This is a Darwin macOS User manipulation class. Main differences are that Darwin:- - Handles accounts in a database managed by dscl(1) - Has no useradd/groupadd - Does not create home directories - User password must be cleartext - UID must be given - System users must ben under 500 This overrides the following methods from the generic class:- - user_exists() - create_user() - remove_user() - modify_user() """ platform = 'Darwin' distribution = None SHADOWFILE = None dscl_directory = '.' fields = [ ('comment', 'RealName'), ('home', 'NFSHomeDirectory'), ('shell', 'UserShell'), ('uid', 'UniqueID'), ('group', 'PrimaryGroupID'), ('hidden', 'IsHidden'), ] def __init__(self, module): super(DarwinUser, self).__init__(module) # make the user hidden if option is set or deffer to system option if self.hidden is None: if self.system: self.hidden = 1 elif self.hidden: self.hidden = 1 else: self.hidden = 0 # add hidden to processing if set if self.hidden is not None: self.fields.append(('hidden', 'IsHidden')) def _get_dscl(self): return [self.module.get_bin_path('dscl', True), self.dscl_directory] def _list_user_groups(self): cmd = self._get_dscl() cmd += ['-search', '/Groups', 'GroupMembership', self.name] (rc, out, err) = self.execute_command(cmd, obey_checkmode=False) groups = [] for line in out.splitlines(): if line.startswith(' ') or line.startswith(')'): continue groups.append(line.split()[0]) return groups def _get_user_property(self, property): '''Return user PROPERTY as given my dscl(1) read or None if not found.''' cmd = self._get_dscl() cmd += ['-read', '/Users/%s' % self.name, property] (rc, out, err) = self.execute_command(cmd, obey_checkmode=False) if rc != 0: return None # from dscl(1) # if property contains embedded spaces, the list will instead be # displayed one entry per line, starting on the line after the key. lines = out.splitlines() # sys.stderr.write('*** |%s| %s -> %s\n' % (property, out, lines)) if len(lines) == 1: return lines[0].split(': ')[1] else: if len(lines) > 2: return '\n'.join([lines[1].strip()] + lines[2:]) else: if len(lines) == 2: return lines[1].strip() else: return None def _get_next_uid(self, system=None): ''' Return the next available uid. If system=True, then uid should be below of 500, if possible. ''' cmd = self._get_dscl() cmd += ['-list', '/Users', 'UniqueID'] (rc, out, err) = self.execute_command(cmd, obey_checkmode=False) if rc != 0: self.module.fail_json( msg="Unable to get the next available uid", rc=rc, out=out, err=err ) max_uid = 0 max_system_uid = 0 for line in out.splitlines(): current_uid = int(line.split(' ')[-1]) if max_uid < current_uid: max_uid = current_uid if max_system_uid < current_uid and current_uid < 500: max_system_uid = current_uid if system and (0 < max_system_uid < 499): return max_system_uid + 1 return max_uid + 1 def _change_user_password(self): '''Change password for SELF.NAME against SELF.PASSWORD. Please note that password must be cleartext. ''' # some documentation on how is stored passwords on OSX: # http://blog.lostpassword.com/2012/07/cracking-mac-os-x-lion-accounts-passwords/ # http://null-byte.wonderhowto.com/how-to/hack-mac-os-x-lion-passwords-0130036/ # http://pastebin.com/RYqxi7Ca # on OSX 10.8+ hash is SALTED-SHA512-PBKDF2 # https://pythonhosted.org/passlib/lib/passlib.hash.pbkdf2_digest.html # https://gist.github.com/nueh/8252572 cmd = self._get_dscl() if self.password: cmd += ['-passwd', '/Users/%s' % self.name, self.password] else: cmd += ['-create', '/Users/%s' % self.name, 'Password', '*'] (rc, out, err) = self.execute_command(cmd) if rc != 0: self.module.fail_json(msg='Error when changing password', err=err, out=out, rc=rc) return (rc, out, err) def _make_group_numerical(self): '''Convert SELF.GROUP to is stringed numerical value suitable for dscl.''' if self.group is None: self.group = 'nogroup' try: self.group = grp.getgrnam(self.group).gr_gid except KeyError: self.module.fail_json(msg='Group "%s" not found. Try to create it first using "group" module.' % self.group) # We need to pass a string to dscl self.group = str(self.group) def __modify_group(self, group, action): '''Add or remove SELF.NAME to or from GROUP depending on ACTION. ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. ''' if action == 'add': option = '-a' else: option = '-d' cmd = ['dseditgroup', '-o', 'edit', option, self.name, '-t', 'user', group] (rc, out, err) = self.execute_command(cmd) if rc != 0: self.module.fail_json(msg='Cannot %s user "%s" to group "%s".' % (action, self.name, group), err=err, out=out, rc=rc) return (rc, out, err) def _modify_group(self): '''Add or remove SELF.NAME to or from GROUP depending on ACTION. ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. ''' rc = 0 out = '' err = '' changed = False current = set(self._list_user_groups()) if self.groups is not None: target = set(self.groups.split(',')) else: target = set([]) if self.append is False: for remove in current - target: (_rc, _err, _out) = self.__modify_group(remove, 'delete') rc += rc out += _out err += _err changed = True for add in target - current: (_rc, _err, _out) = self.__modify_group(add, 'add') rc += _rc out += _out err += _err changed = True return (rc, err, out, changed) def _update_system_user(self): '''Hide or show user on login window according SELF.SYSTEM. Returns 0 if a change has been made, None otherwise.''' plist_file = '/Library/Preferences/com.apple.loginwindow.plist' # http://support.apple.com/kb/HT5017?viewlocale=en_US cmd = ['defaults', 'read', plist_file, 'HiddenUsersList'] (rc, out, err) = self.execute_command(cmd, obey_checkmode=False) # returned value is # ( # "_userA", # "_UserB", # userc # ) hidden_users = [] for x in out.splitlines()[1:-1]: try: x = x.split('"')[1] except IndexError: x = x.strip() hidden_users.append(x) if self.system: if self.name not in hidden_users: cmd = ['defaults', 'write', plist_file, 'HiddenUsersList', '-array-add', self.name] (rc, out, err) = self.execute_command(cmd) if rc != 0: self.module.fail_json(msg='Cannot user "%s" to hidden user list.' % self.name, err=err, out=out, rc=rc) return 0 else: if self.name in hidden_users: del (hidden_users[hidden_users.index(self.name)]) cmd = ['defaults', 'write', plist_file, 'HiddenUsersList', '-array'] + hidden_users (rc, out, err) = self.execute_command(cmd) if rc != 0: self.module.fail_json(msg='Cannot remove user "%s" from hidden user list.' % self.name, err=err, out=out, rc=rc) return 0 def user_exists(self): '''Check is SELF.NAME is a known user on the system.''' cmd = self._get_dscl() cmd += ['-list', '/Users/%s' % self.name] (rc, out, err) = self.execute_command(cmd, obey_checkmode=False) return rc == 0 def remove_user(self): '''Delete SELF.NAME. If SELF.FORCE is true, remove its home directory.''' info = self.user_info() cmd = self._get_dscl() cmd += ['-delete', '/Users/%s' % self.name] (rc, out, err) = self.execute_command(cmd) if rc != 0: self.module.fail_json(msg='Cannot delete user "%s".' % self.name, err=err, out=out, rc=rc) if self.force: if os.path.exists(info[5]): shutil.rmtree(info[5]) out += "Removed %s" % info[5] return (rc, out, err) def create_user(self, command_name='dscl'): cmd = self._get_dscl() cmd += ['-create', '/Users/%s' % self.name] (rc, err, out) = self.execute_command(cmd) if rc != 0: self.module.fail_json(msg='Cannot create user "%s".' % self.name, err=err, out=out, rc=rc) self._make_group_numerical() if self.uid is None: self.uid = str(self._get_next_uid(self.system)) # Homedir is not created by default if self.create_home: if self.home is None: self.home = '/Users/%s' % self.name if not self.module.check_mode: if not os.path.exists(self.home): os.makedirs(self.home) self.chown_homedir(int(self.uid), int(self.group), self.home) # dscl sets shell to /usr/bin/false when UserShell is not specified # so set the shell to /bin/bash when the user is not a system user if not self.system and self.shell is None: self.shell = '/bin/bash' for field in self.fields: if field[0] in self.__dict__ and self.__dict__[field[0]]: cmd = self._get_dscl() cmd += ['-create', '/Users/%s' % self.name, field[1], self.__dict__[field[0]]] (rc, _err, _out) = self.execute_command(cmd) if rc != 0: self.module.fail_json(msg='Cannot add property "%s" to user "%s".' % (field[0], self.name), err=err, out=out, rc=rc) out += _out err += _err if rc != 0: return (rc, _err, _out) (rc, _err, _out) = self._change_user_password() out += _out err += _err self._update_system_user() # here we don't care about change status since it is a creation, # thus changed is always true. if self.groups: (rc, _out, _err, changed) = self._modify_group() out += _out err += _err return (rc, err, out) def modify_user(self): changed = None out = '' err = '' if self.group: self._make_group_numerical() for field in self.fields: if field[0] in self.__dict__ and self.__dict__[field[0]]: current = self._get_user_property(field[1]) if current is None or current != self.__dict__[field[0]]: cmd = self._get_dscl() cmd += ['-create', '/Users/%s' % self.name, field[1], self.__dict__[field[0]]] (rc, _err, _out) = self.execute_command(cmd) if rc != 0: self.module.fail_json( msg='Cannot update property "%s" for user "%s".' % (field[0], self.name), err=err, out=out, rc=rc) changed = rc out += _out err += _err if self.update_password == 'always' and self.password is not None: (rc, _err, _out) = self._change_user_password() out += _out err += _err changed = rc if self.groups: (rc, _out, _err, _changed) = self._modify_group() out += _out err += _err if _changed is True: changed = rc rc = self._update_system_user() if rc == 0: changed = rc return (changed, out, err) class AIX(User): """ This is a AIX User manipulation class. This overrides the following methods from the generic class:- - create_user() - remove_user() - modify_user() - parse_shadow_file() """ platform = 'AIX' distribution = None SHADOWFILE = '/etc/security/passwd' def remove_user(self): cmd = [self.module.get_bin_path('userdel', True)] if self.remove: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def create_user_useradd(self, command_name='useradd'): cmd = [self.module.get_bin_path(command_name, True)] if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) cmd.append('-g') cmd.append(self.group) if self.groups is not None and len(self.groups): groups = self.get_groups_set() cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None: cmd.append('-c') cmd.append(self.comment) if self.home is not None: cmd.append('-d') cmd.append(self.home) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if self.create_home: cmd.append('-m') if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) cmd.append(self.name) (rc, out, err) = self.execute_command(cmd) # set password with chpasswd if self.password is not None: cmd = [] cmd.append(self.module.get_bin_path('chpasswd', True)) cmd.append('-e') cmd.append('-c') self.execute_command(cmd, data="%s:%s" % (self.name, self.password)) return (rc, out, err) def modify_user_usermod(self): cmd = [self.module.get_bin_path('usermod', True)] info = self.user_info() if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) ginfo = self.group_info(self.group) if info[3] != ginfo[2]: cmd.append('-g') cmd.append(self.group) if self.groups is not None: current_groups = self.user_group_membership() groups_need_mod = False groups = [] if self.groups == '': if current_groups and not self.append: groups_need_mod = True else: groups = self.get_groups_set() group_diff = set(current_groups).symmetric_difference(groups) if group_diff: if self.append: for g in groups: if g in group_diff: groups_need_mod = True break else: groups_need_mod = True if groups_need_mod: cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None and info[4] != self.comment: cmd.append('-c') cmd.append(self.comment) if self.home is not None and info[5] != self.home: if self.move_home: cmd.append('-m') cmd.append('-d') cmd.append(self.home) if self.shell is not None and info[6] != self.shell: cmd.append('-s') cmd.append(self.shell) # skip if no changes to be made if len(cmd) == 1: (rc, out, err) = (None, '', '') else: cmd.append(self.name) (rc, out, err) = self.execute_command(cmd) # set password with chpasswd if self.update_password == 'always' and self.password is not None and info[1] != self.password: cmd = [] cmd.append(self.module.get_bin_path('chpasswd', True)) cmd.append('-e') cmd.append('-c') (rc2, out2, err2) = self.execute_command(cmd, data="%s:%s" % (self.name, self.password)) else: (rc2, out2, err2) = (None, '', '') if rc is not None: return (rc, out + out2, err + err2) else: return (rc2, out + out2, err + err2) def parse_shadow_file(self): """Example AIX shadowfile data: nobody: password = * operator1: password = {ssha512}06$xxxxxxxxxxxx.... lastupdate = 1549558094 test1: password = * lastupdate = 1553695126 """ b_name = to_bytes(self.name) b_passwd = b'' b_expires = b'' if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK): with open(self.SHADOWFILE, 'rb') as bf: b_lines = bf.readlines() b_passwd_line = b'' b_expires_line = b'' try: for index, b_line in enumerate(b_lines): # Get password and lastupdate lines which come after the username if b_line.startswith(b'%s:' % b_name): b_passwd_line = b_lines[index + 1] b_expires_line = b_lines[index + 2] break # Sanity check the lines because sometimes both are not present if b' = ' in b_passwd_line: b_passwd = b_passwd_line.split(b' = ', 1)[-1].strip() if b' = ' in b_expires_line: b_expires = b_expires_line.split(b' = ', 1)[-1].strip() except IndexError: self.module.fail_json(msg='Failed to parse shadow file %s' % self.SHADOWFILE) passwd = to_native(b_passwd) expires = to_native(b_expires) or -1 return passwd, expires class HPUX(User): """ This is a HP-UX User manipulation class. This overrides the following methods from the generic class:- - create_user() - remove_user() - modify_user() """ platform = 'HP-UX' distribution = None SHADOWFILE = '/etc/shadow' def create_user(self): cmd = ['/usr/sam/lbin/useradd.sam'] if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) cmd.append('-g') cmd.append(self.group) if self.groups is not None and len(self.groups): groups = self.get_groups_set() cmd.append('-G') cmd.append(','.join(groups)) if self.comment is not None: cmd.append('-c') cmd.append(self.comment) if self.home is not None: cmd.append('-d') cmd.append(self.home) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if self.password is not None: cmd.append('-p') cmd.append(self.password) if self.create_home: cmd.append('-m') else: cmd.append('-M') if self.system: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def remove_user(self): cmd = ['/usr/sam/lbin/userdel.sam'] if self.force: cmd.append('-F') if self.remove: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def modify_user(self): cmd = ['/usr/sam/lbin/usermod.sam'] info = self.user_info() if self.uid is not None and info[2] != int(self.uid): cmd.append('-u') cmd.append(self.uid) if self.non_unique: cmd.append('-o') if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg="Group %s does not exist" % self.group) ginfo = self.group_info(self.group) if info[3] != ginfo[2]: cmd.append('-g') cmd.append(self.group) if self.groups is not None: current_groups = self.user_group_membership() groups_need_mod = False groups = [] if self.groups == '': if current_groups and not self.append: groups_need_mod = True else: groups = self.get_groups_set(remove_existing=False) group_diff = set(current_groups).symmetric_difference(groups) if group_diff: if self.append: for g in groups: if g in group_diff: groups_need_mod = True break else: groups_need_mod = True if groups_need_mod: cmd.append('-G') new_groups = groups if self.append: new_groups = groups | set(current_groups) cmd.append(','.join(new_groups)) if self.comment is not None and info[4] != self.comment: cmd.append('-c') cmd.append(self.comment) if self.home is not None and info[5] != self.home: cmd.append('-d') cmd.append(self.home) if self.move_home: cmd.append('-m') if self.shell is not None and info[6] != self.shell: cmd.append('-s') cmd.append(self.shell) if self.update_password == 'always' and self.password is not None and info[1] != self.password: cmd.append('-F') cmd.append('-p') cmd.append(self.password) # skip if no changes to be made if len(cmd) == 1: return (None, '', '') cmd.append(self.name) return self.execute_command(cmd) class BusyBox(User): """ This is the BusyBox class for use on systems that have adduser, deluser, and delgroup commands. It overrides the following methods: - create_user() - remove_user() - modify_user() """ def create_user(self): cmd = [self.module.get_bin_path('adduser', True)] cmd.append('-D') if self.uid is not None: cmd.append('-u') cmd.append(self.uid) if self.group is not None: if not self.group_exists(self.group): self.module.fail_json(msg='Group {0} does not exist'.format(self.group)) cmd.append('-G') cmd.append(self.group) if self.comment is not None: cmd.append('-g') cmd.append(self.comment) if self.home is not None: cmd.append('-h') cmd.append(self.home) if self.shell is not None: cmd.append('-s') cmd.append(self.shell) if not self.create_home: cmd.append('-H') if self.skeleton is not None: cmd.append('-k') cmd.append(self.skeleton) if self.system: cmd.append('-S') cmd.append(self.name) rc, out, err = self.execute_command(cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) if self.password is not None: cmd = [self.module.get_bin_path('chpasswd', True)] cmd.append('--encrypted') data = '{name}:{password}'.format(name=self.name, password=self.password) rc, out, err = self.execute_command(cmd, data=data) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) # Add to additional groups if self.groups is not None and len(self.groups): groups = self.get_groups_set() add_cmd_bin = self.module.get_bin_path('adduser', True) for group in groups: cmd = [add_cmd_bin, self.name, group] rc, out, err = self.execute_command(cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) return rc, out, err def remove_user(self): cmd = [ self.module.get_bin_path('deluser', True), self.name ] if self.remove: cmd.append('--remove-home') return self.execute_command(cmd) def modify_user(self): current_groups = self.user_group_membership() groups = [] rc = None out = '' err = '' info = self.user_info() add_cmd_bin = self.module.get_bin_path('adduser', True) remove_cmd_bin = self.module.get_bin_path('delgroup', True) # Manage group membership if self.groups is not None and len(self.groups): groups = self.get_groups_set() group_diff = set(current_groups).symmetric_difference(groups) if group_diff: for g in groups: if g in group_diff: add_cmd = [add_cmd_bin, self.name, g] rc, out, err = self.execute_command(add_cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) for g in group_diff: if g not in groups and not self.append: remove_cmd = [remove_cmd_bin, self.name, g] rc, out, err = self.execute_command(remove_cmd) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) # Manage password if self.password is not None: if info[1] != self.password: cmd = [self.module.get_bin_path('chpasswd', True)] cmd.append('--encrypted') data = '{name}:{password}'.format(name=self.name, password=self.password) rc, out, err = self.execute_command(cmd, data=data) if rc is not None and rc != 0: self.module.fail_json(name=self.name, msg=err, rc=rc) return rc, out, err class Alpine(BusyBox): """ This is the Alpine User manipulation class. It inherits the BusyBox class behaviors such as using adduser and deluser commands. """ platform = 'Linux' distribution = 'Alpine' def main(): ssh_defaults = dict( bits=0, type='rsa', passphrase=None, comment='ansible-generated on %s' % socket.gethostname() ) module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='present', choices=['absent', 'present']), name=dict(type='str', required=True, aliases=['user']), uid=dict(type='int'), non_unique=dict(type='bool', default=False), group=dict(type='str'), groups=dict(type='list'), comment=dict(type='str'), home=dict(type='path'), shell=dict(type='str'), password=dict(type='str', no_log=True), login_class=dict(type='str'), # following options are specific to macOS hidden=dict(type='bool'), # following options are specific to selinux seuser=dict(type='str'), # following options are specific to userdel force=dict(type='bool', default=False), remove=dict(type='bool', default=False), # following options are specific to useradd create_home=dict(type='bool', default=True, aliases=['createhome']), skeleton=dict(type='str'), system=dict(type='bool', default=False), # following options are specific to usermod move_home=dict(type='bool', default=False), append=dict(type='bool', default=False), # following are specific to ssh key generation generate_ssh_key=dict(type='bool'), ssh_key_bits=dict(type='int', default=ssh_defaults['bits']), ssh_key_type=dict(type='str', default=ssh_defaults['type']), ssh_key_file=dict(type='path'), ssh_key_comment=dict(type='str', default=ssh_defaults['comment']), ssh_key_passphrase=dict(type='str', no_log=True), update_password=dict(type='str', default='always', choices=['always', 'on_create']), expires=dict(type='float'), password_lock=dict(type='bool'), local=dict(type='bool'), profile=dict(type='str'), authorization=dict(type='str'), role=dict(type='str'), ), supports_check_mode=True, mutually_exclusive=[ ('local', 'groups'), ('local', 'append') ] ) user = User(module) user.check_password_encrypted() module.debug('User instantiated - platform %s' % user.platform) if user.distribution: module.debug('User instantiated - distribution %s' % user.distribution) rc = None out = '' err = '' result = {} result['name'] = user.name result['state'] = user.state if user.state == 'absent': if user.user_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = user.remove_user() if rc != 0: module.fail_json(name=user.name, msg=err, rc=rc) result['force'] = user.force result['remove'] = user.remove elif user.state == 'present': if not user.user_exists(): if module.check_mode: module.exit_json(changed=True) # Check to see if the provided home path contains parent directories # that do not exist. path_needs_parents = False if user.home: parent = os.path.dirname(user.home) if not os.path.isdir(parent): path_needs_parents = True (rc, out, err) = user.create_user() # If the home path had parent directories that needed to be created, # make sure file permissions are correct in the created home directory. if path_needs_parents: info = user.user_info() if info is not False: user.chown_homedir(info[2], info[3], user.home) if module.check_mode: result['system'] = user.name else: result['system'] = user.system result['create_home'] = user.create_home else: # modify user (note: this function is check mode aware) (rc, out, err) = user.modify_user() result['append'] = user.append result['move_home'] = user.move_home if rc is not None and rc != 0: module.fail_json(name=user.name, msg=err, rc=rc) if user.password is not None: result['password'] = 'NOT_LOGGING_PASSWORD' if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err if user.user_exists() and user.state == 'present': info = user.user_info() if info is False: result['msg'] = "failed to look up user name: %s" % user.name result['failed'] = True result['uid'] = info[2] result['group'] = info[3] result['comment'] = info[4] result['home'] = info[5] result['shell'] = info[6] if user.groups is not None: result['groups'] = user.groups # handle missing homedirs info = user.user_info() if user.home is None: user.home = info[5] if not os.path.exists(user.home) and user.create_home: if not module.check_mode: user.create_homedir(user.home) user.chown_homedir(info[2], info[3], user.home) result['changed'] = True # deal with ssh key if user.sshkeygen: # generate ssh key (note: this function is check mode aware) (rc, out, err) = user.ssh_key_gen() if rc is not None and rc != 0: module.fail_json(name=user.name, msg=err, rc=rc) if rc == 0: result['changed'] = True (rc, out, err) = user.ssh_key_fingerprint() if rc == 0: result['ssh_fingerprint'] = out.strip() else: result['ssh_fingerprint'] = err.strip() result['ssh_key_file'] = user.get_ssh_key_path() result['ssh_public_key'] = user.get_ssh_public_key() module.exit_json(**result) # import module snippets if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
62,286
zabbix_host tests are not run by CI
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY `zabbix_host` functional test depends on Ubuntu 14.04. But this OS is not run by the CI since c8f2becb7a3d15b6c8dd8aa29eb8d0e6b7d7a9ae. <!--- Explain the problem briefly below --> ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME zabbix_host setup_zabbix <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ```
https://github.com/ansible/ansible/issues/62286
https://github.com/ansible/ansible/pull/63744
07ed860c2b5c1fdabdd30b628e8f44c829d243b6
57c36e037815b6344c24922c069b6e0b2d0bcc71
2019-09-13T15:52:15Z
python
2019-10-25T10:28:20Z
test/integration/targets/setup_zabbix/defaults/main.yml
--- db_name: 'zabbix' db_user: 'zabbix' db_password: 'fLhijUs3PgekNhwJ' zabbix_release_deb: 'http://repo.zabbix.com/zabbix/3.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_3.4-1+trusty_all.deb' zabbix_packages: - zabbix-server-mysql - zabbix-frontend-php
closed
ansible/ansible
https://github.com/ansible/ansible
62,286
zabbix_host tests are not run by CI
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY `zabbix_host` functional test depends on Ubuntu 14.04. But this OS is not run by the CI since c8f2becb7a3d15b6c8dd8aa29eb8d0e6b7d7a9ae. <!--- Explain the problem briefly below --> ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME zabbix_host setup_zabbix <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ```
https://github.com/ansible/ansible/issues/62286
https://github.com/ansible/ansible/pull/63744
07ed860c2b5c1fdabdd30b628e8f44c829d243b6
57c36e037815b6344c24922c069b6e0b2d0bcc71
2019-09-13T15:52:15Z
python
2019-10-25T10:28:20Z
test/integration/targets/setup_zabbix/tasks/main.yml
--- # This integration test is only for Ubuntu 14.04 at the moment. This makes # installation of a Zabbix quite a bit easier. - include: setup.yml when: ansible_distribution == 'Ubuntu' and ansible_distribution_release == 'trusty'
closed
ansible/ansible
https://github.com/ansible/ansible
62,286
zabbix_host tests are not run by CI
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY `zabbix_host` functional test depends on Ubuntu 14.04. But this OS is not run by the CI since c8f2becb7a3d15b6c8dd8aa29eb8d0e6b7d7a9ae. <!--- Explain the problem briefly below --> ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME zabbix_host setup_zabbix <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ```
https://github.com/ansible/ansible/issues/62286
https://github.com/ansible/ansible/pull/63744
07ed860c2b5c1fdabdd30b628e8f44c829d243b6
57c36e037815b6344c24922c069b6e0b2d0bcc71
2019-09-13T15:52:15Z
python
2019-10-25T10:28:20Z
test/integration/targets/setup_zabbix/tasks/setup.yml
# sets up and starts Zabbix with default settings (works on Ubuntu 14.04, # possibly more) using a MySQL database. - name: create mysql user {{ db_user }} mysql_user: name: "{{ db_user }}" password: "{{ db_password }}" state: present priv: "{{ db_name }}.*:ALL" - name: install zabbix repository apt: deb={{ zabbix_release_deb }} state=present - name: install zabbix debian dependencies apt: name={{ item }} state=latest update_cache=yes with_items: "{{ zabbix_packages }}" - name: install zabbix-api python package pip: name: zabbix-api - name: import initial zabbix database mysql_db: name: "{{ db_name }}" login_user: "{{ db_user }}" login_password: "{{ db_password }}" state: import target: /usr/share/doc/zabbix-server-mysql/create.sql.gz - name: deploy zabbix-server configuration template: src: zabbix_server.conf.j2 dest: /etc/zabbix/zabbix_server.conf owner: zabbix group: zabbix mode: 0644 - name: deploy zabbix web frontend configuration template: src: zabbix.conf.php.j2 dest: /etc/zabbix/web/zabbix.conf.php mode: 0644 - name: restart zabbix-server service: name=zabbix-server state=restarted enabled=yes - name: restart apache2 service: name=apache2 state=restarted enabled=yes
closed
ansible/ansible
https://github.com/ansible/ansible
62,286
zabbix_host tests are not run by CI
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY `zabbix_host` functional test depends on Ubuntu 14.04. But this OS is not run by the CI since c8f2becb7a3d15b6c8dd8aa29eb8d0e6b7d7a9ae. <!--- Explain the problem briefly below --> ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME zabbix_host setup_zabbix <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ```
https://github.com/ansible/ansible/issues/62286
https://github.com/ansible/ansible/pull/63744
07ed860c2b5c1fdabdd30b628e8f44c829d243b6
57c36e037815b6344c24922c069b6e0b2d0bcc71
2019-09-13T15:52:15Z
python
2019-10-25T10:28:20Z
test/integration/targets/setup_zabbix/templates/zabbix_server.conf.j2
LogFile=/tmp/zabbix_server.log DBName={{ db_name }} DBUser={{ db_user }} DBPassword={{ db_password }} Timeout=4 LogSlowQueries=3000
closed
ansible/ansible
https://github.com/ansible/ansible
62,286
zabbix_host tests are not run by CI
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY `zabbix_host` functional test depends on Ubuntu 14.04. But this OS is not run by the CI since c8f2becb7a3d15b6c8dd8aa29eb8d0e6b7d7a9ae. <!--- Explain the problem briefly below --> ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME zabbix_host setup_zabbix <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ```
https://github.com/ansible/ansible/issues/62286
https://github.com/ansible/ansible/pull/63744
07ed860c2b5c1fdabdd30b628e8f44c829d243b6
57c36e037815b6344c24922c069b6e0b2d0bcc71
2019-09-13T15:52:15Z
python
2019-10-25T10:28:20Z
test/integration/targets/zabbix_host/tasks/main.yml
--- # setup stuff not testing zabbix_host - include: zabbix_host_setup.yml when: ansible_distribution == 'Ubuntu' and ansible_distribution_release == 'trusty' # zabbix_host module tests - include: zabbix_host_tests.yml when: ansible_distribution == 'Ubuntu' and ansible_distribution_release == 'trusty' # documentation example tests - include: zabbix_host_doc.yml when: ansible_distribution == 'Ubuntu' and ansible_distribution_release == 'trusty' # tear down stuff set up earlier - include: zabbix_host_teardown.yml when: ansible_distribution == 'Ubuntu' and ansible_distribution_release == 'trusty'
closed
ansible/ansible
https://github.com/ansible/ansible
63,502
ovirt_vm_facts no bootable fact if false
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY When gathering facts on an oVirt VM the bootable variable in the disk attachment is only filled out when the flag is true, if false the variable stays empty and will be non existing. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lib/ansible/modules/cloud/ovirt/ovirt_vm_info.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 3.6.8 (default, Oct 7 2019, 12:59:55) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below DEFAULT_ACTION_PLUGIN_PATH(/etc/ansible/ansible.cfg) = ['/usr/local/lib/python3.6/dist-packages/ara/plugins/actions'] DEFAULT_CALLBACK_PLUGIN_PATH(/etc/ansible/ansible.cfg) = ['/usr/local/lib/python3.6/dist-packages/ara/plugins/callbacks'] DEFAULT_CALLBACK_WHITELIST(/etc/ansible/ansible.cfg) = ['slack'] DEFAULT_HOST_LIST(/etc/ansible/ansible.cfg) = ['/home/user/ansible-store/inventory'] DEFAULT_JINJA2_EXTENSIONS(/etc/ansible/ansible.cfg) = jinja2.ext.do,jinja2.ext.i18n,jinja2.ext.loopcontrols DEFAULT_LOG_PATH(/etc/ansible/ansible.cfg) = /var/log/ansible DEFAULT_ROLES_PATH(/etc/ansible/ansible.cfg) = ['/home/user/ansible-store/roles'] DEFAULT_TIMEOUT(/etc/ansible/ansible.cfg) = 300 DEFAULT_VAULT_PASSWORD_FILE(/etc/ansible/ansible.cfg) = /etc/ansible/.vault_pass HOST_KEY_CHECKING(/etc/ansible/ansible.cfg) = False INVENTORY_IGNORE_EXTS(/etc/ansible/ansible.cfg) = ['.pyc', '.pyo', '.swp', '.bak', '~', '.rpm', '.md', '.txt', '~', '.orig', '.ini', '.cfg', '.retry', '.py'] RETRY_FILES_ENABLED(/etc/ansible/ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Ansible Host: Ubuntu 18.04.2 LTS Client: CentOS Linux release 7.4.1708 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Ansible playbook that uses the module ovirt_vm_facts and then uses debug to display the gathered facts. <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: VM Fact Gathering ovirt_vm_facts: auth: "{{ ovirt_auth }}" fetch_nested: yes nested_attributes: - bootable all_content: yes pattern: name=testvm01 - debug: var: ovirt_vms[0].disk_attachments ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> ``` "ovirt_vms[0].disk_attachments": [ { "bootable": false, "href": "/ovirt-engine/api/vms/0bf62b1b-dc74-4a5c-bc09-62bd5f860911/diskattachments/51ec34a4-fbbd-4ff9-8f97-91a1c732a5f5", "id": "51ec34a4-fbbd-4ff9-8f97-91a1c732a5f5" }, { "bootable": true, "href": "/ovirt-engine/api/vms/0bf62b1b-dc74-4a5c-bc09-62bd5f860911/diskattachments/6f92958a-8c25-4733-af97-e860a375d2c4", "id": "6f92958a-8c25-4733-af97-e860a375d2c4" } ] } ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below "ovirt_vms[0].disk_attachments": [ { "href": "/ovirt-engine/api/vms/0bf62b1b-dc74-4a5c-bc09-62bd5f860911/diskattachments/51ec34a4-fbbd-4ff9-8f97-91a1c732a5f5", "id": "51ec34a4-fbbd-4ff9-8f97-91a1c732a5f5" }, { "bootable": true, "href": "/ovirt-engine/api/vms/0bf62b1b-dc74-4a5c-bc09-62bd5f860911/diskattachments/6f92958a-8c25-4733-af97-e860a375d2c4", "id": "6f92958a-8c25-4733-af97-e860a375d2c4" } ] } ```
https://github.com/ansible/ansible/issues/63502
https://github.com/ansible/ansible/pull/63908
5e9638c869225bb32608bd56d7fcd370edcfcc3a
92d621202601ec8ac1aed020f6c338655d8a660d
2019-10-15T09:34:36Z
python
2019-10-25T13:51:45Z
lib/ansible/module_utils/ovirt.py
# -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # import inspect import os import time from abc import ABCMeta, abstractmethod from datetime import datetime from distutils.version import LooseVersion from ansible.module_utils.cloud import CloudRetry from ansible.module_utils.common._collections_compat import Mapping try: from enum import Enum # enum is a ovirtsdk4 requirement import ovirtsdk4 as sdk import ovirtsdk4.version as sdk_version import ovirtsdk4.types as otypes HAS_SDK = LooseVersion(sdk_version.VERSION) >= LooseVersion('4.3.0') except ImportError: HAS_SDK = False BYTES_MAP = { 'kib': 2**10, 'mib': 2**20, 'gib': 2**30, 'tib': 2**40, 'pib': 2**50, } def check_sdk(module): if not HAS_SDK: module.fail_json( msg='ovirtsdk4 version 4.3.0 or higher is required for this module' ) def get_dict_of_struct(struct, connection=None, fetch_nested=False, attributes=None): """ Convert SDK Struct type into dictionary. """ res = {} def resolve_href(value): # Fetch nested values of struct: try: value = connection.follow_link(value) except sdk.Error: value = None nested_obj = dict( (attr, convert_value(getattr(value, attr))) for attr in attributes if getattr(value, attr, None) ) nested_obj['id'] = getattr(value, 'id', None) nested_obj['href'] = getattr(value, 'href', None) return nested_obj def remove_underscore(val): if val.startswith('_'): val = val[1:] remove_underscore(val) return val def convert_value(value): nested = False if isinstance(value, sdk.Struct): if not fetch_nested or not value.href: return get_dict_of_struct(value) return resolve_href(value) elif isinstance(value, Enum) or isinstance(value, datetime): return str(value) elif isinstance(value, list) or isinstance(value, sdk.List): if isinstance(value, sdk.List) and fetch_nested and value.href: try: value = connection.follow_link(value) nested = True except sdk.Error: value = [] ret = [] for i in value: if isinstance(i, sdk.Struct): if not nested and fetch_nested and i.href: ret.append(resolve_href(i)) elif not nested: ret.append(get_dict_of_struct(i)) else: nested_obj = dict( (attr, convert_value(getattr(i, attr))) for attr in attributes if getattr(i, attr, None) ) nested_obj['id'] = getattr(i, 'id', None) ret.append(nested_obj) elif isinstance(i, Enum): ret.append(str(i)) else: ret.append(i) return ret else: return value if struct is not None: for key, value in struct.__dict__.items(): if value is None: continue key = remove_underscore(key) res[key] = convert_value(value) return res def engine_version(connection): """ Return string representation of oVirt engine version. """ engine_api = connection.system_service().get() engine_version = engine_api.product_info.version return '%s.%s' % (engine_version.major, engine_version.minor) def create_connection(auth): """ Create a connection to Python SDK, from task `auth` parameter. If user doesnt't have SSO token the `auth` dictionary has following parameters mandatory: url, username, password If user has SSO token the `auth` dictionary has following parameters mandatory: url, token The `ca_file` parameter is mandatory in case user want to use secure connection, in case user want to use insecure connection, it's mandatory to send insecure=True. :param auth: dictionary which contains needed values for connection creation :return: Python SDK connection """ url = auth.get('url') if url is None and auth.get('hostname') is not None: url = 'https://{0}/ovirt-engine/api'.format(auth.get('hostname')) return sdk.Connection( url=url, username=auth.get('username'), password=auth.get('password'), ca_file=auth.get('ca_file', None), insecure=auth.get('insecure', False), token=auth.get('token', None), kerberos=auth.get('kerberos', None), headers=auth.get('headers', None), ) def convert_to_bytes(param): """ This method convert units to bytes, which follow IEC standard. :param param: value to be converted """ if param is None: return None # Get rid of whitespaces: param = ''.join(param.split()) # Convert to bytes: if len(param) > 3 and param[-3].lower() in ['k', 'm', 'g', 't', 'p']: return int(param[:-3]) * BYTES_MAP.get(param[-3:].lower(), 1) elif param.isdigit(): return int(param) * 2**10 else: raise ValueError( "Unsupported value(IEC supported): '{value}'".format(value=param) ) def follow_link(connection, link): """ This method returns the entity of the element which link points to. :param connection: connection to the Python SDK :param link: link of the entity :return: entity which link points to """ if link: return connection.follow_link(link) else: return None def get_link_name(connection, link): """ This method returns the name of the element which link points to. :param connection: connection to the Python SDK :param link: link of the entity :return: name of the entity, which link points to """ if link: return connection.follow_link(link).name else: return None def equal(param1, param2, ignore_case=False): """ Compare two parameters and return if they are equal. This parameter doesn't run equal operation if first parameter is None. With this approach we don't run equal operation in case user don't specify parameter in their task. :param param1: user inputted parameter :param param2: value of entity parameter :return: True if parameters are equal or first parameter is None, otherwise False """ if param1 is not None: if ignore_case: return param1.lower() == param2.lower() return param1 == param2 return True def search_by_attributes(service, list_params=None, **kwargs): """ Search for the entity by attributes. Nested entities don't support search via REST, so in case using search for nested entity we return all entities and filter them by specified attributes. """ list_params = list_params or {} # Check if 'list' method support search(look for search parameter): if 'search' in inspect.getargspec(service.list)[0]: res = service.list( # There must be double quotes around name, because some oVirt resources it's possible to create then with space in name. search=' and '.join('{0}="{1}"'.format(k, v) for k, v in kwargs.items()), **list_params ) else: res = [ e for e in service.list(**list_params) if len([ k for k, v in kwargs.items() if getattr(e, k, None) == v ]) == len(kwargs) ] res = res or [None] return res[0] def search_by_name(service, name, **kwargs): """ Search for the entity by its name. Nested entities don't support search via REST, so in case using search for nested entity we return all entities and filter them by name. :param service: service of the entity :param name: name of the entity :return: Entity object returned by Python SDK """ # Check if 'list' method support search(look for search parameter): if 'search' in inspect.getargspec(service.list)[0]: res = service.list( # There must be double quotes around name, because some oVirt resources it's possible to create then with space in name. search='name="{name}"'.format(name=name) ) else: res = [e for e in service.list() if e.name == name] if kwargs: res = [ e for e in service.list() if len([ k for k, v in kwargs.items() if getattr(e, k, None) == v ]) == len(kwargs) ] res = res or [None] return res[0] def get_entity(service, get_params=None): """ Ignore SDK Error in case of getting an entity from service. """ entity = None try: if get_params is not None: entity = service.get(**get_params) else: entity = service.get() except sdk.Error: # We can get here 404, we should ignore it, in case # of removing entity for example. pass return entity def get_id_by_name(service, name, raise_error=True, ignore_case=False): """ Search an entity ID by it's name. """ entity = search_by_name(service, name) if entity is not None: return entity.id if raise_error: raise Exception("Entity '%s' was not found." % name) def wait( service, condition, fail_condition=lambda e: False, timeout=180, wait=True, poll_interval=3, ): """ Wait until entity fulfill expected condition. :param service: service of the entity :param condition: condition to be fulfilled :param fail_condition: if this condition is true, raise Exception :param timeout: max time to wait in seconds :param wait: if True wait for condition, if False don't wait :param poll_interval: Number of seconds we should wait until next condition check """ # Wait until the desired state of the entity: if wait: start = time.time() while time.time() < start + timeout: # Exit if the condition of entity is valid: entity = get_entity(service) if condition(entity): return elif fail_condition(entity): raise Exception("Error while waiting on result state of the entity.") # Sleep for `poll_interval` seconds if none of the conditions apply: time.sleep(float(poll_interval)) raise Exception("Timeout exceed while waiting on result state of the entity.") def __get_auth_dict(): OVIRT_URL = os.environ.get('OVIRT_URL') OVIRT_HOSTNAME = os.environ.get('OVIRT_HOSTNAME') OVIRT_USERNAME = os.environ.get('OVIRT_USERNAME') OVIRT_PASSWORD = os.environ.get('OVIRT_PASSWORD') OVIRT_TOKEN = os.environ.get('OVIRT_TOKEN') OVIRT_CAFILE = os.environ.get('OVIRT_CAFILE') OVIRT_INSECURE = OVIRT_CAFILE is None env_vars = None if OVIRT_URL is None and OVIRT_HOSTNAME is not None: OVIRT_URL = 'https://{0}/ovirt-engine/api'.format(OVIRT_HOSTNAME) if OVIRT_URL and ((OVIRT_USERNAME and OVIRT_PASSWORD) or OVIRT_TOKEN): env_vars = { 'url': OVIRT_URL, 'username': OVIRT_USERNAME, 'password': OVIRT_PASSWORD, 'insecure': OVIRT_INSECURE, 'token': OVIRT_TOKEN, 'ca_file': OVIRT_CAFILE, } if env_vars is not None: auth = dict(default=env_vars, type='dict') else: auth = dict(required=True, type='dict') return auth def ovirt_info_full_argument_spec(**kwargs): """ Extend parameters of info module with parameters which are common to all oVirt info modules. :param kwargs: kwargs to be extended :return: extended dictionary with common parameters """ spec = dict( auth=__get_auth_dict(), fetch_nested=dict(default=False, type='bool'), nested_attributes=dict(type='list', default=list()), ) spec.update(kwargs) return spec # Left for third-party module compatibility def ovirt_facts_full_argument_spec(**kwargs): """ This is deprecated. Please use ovirt_info_full_argument_spec instead! :param kwargs: kwargs to be extended :return: extended dictionary with common parameters """ return ovirt_info_full_argument_spec(**kwargs) def ovirt_full_argument_spec(**kwargs): """ Extend parameters of module with parameters which are common to all oVirt modules. :param kwargs: kwargs to be extended :return: extended dictionary with common parameters """ spec = dict( auth=__get_auth_dict(), timeout=dict(default=180, type='int'), wait=dict(default=True, type='bool'), poll_interval=dict(default=3, type='int'), fetch_nested=dict(default=False, type='bool'), nested_attributes=dict(type='list', default=list()), ) spec.update(kwargs) return spec def check_params(module): """ Most modules must have either `name` or `id` specified. """ if module.params.get('name') is None and module.params.get('id') is None: module.fail_json(msg='"name" or "id" is required') def engine_supported(connection, version): return LooseVersion(engine_version(connection)) >= LooseVersion(version) def check_support(version, connection, module, params): """ Check if parameters used by user are supported by oVirt Python SDK and oVirt engine. """ api_version = LooseVersion(engine_version(connection)) version = LooseVersion(version) for param in params: if module.params.get(param) is not None: return LooseVersion(sdk_version.VERSION) >= version and api_version >= version return True class BaseModule(object): """ This is base class for oVirt modules. oVirt modules should inherit this class and override method to customize specific needs of the module. The only abstract method of this class is `build_entity`, which must to be implemented in child class. """ __metaclass__ = ABCMeta def __init__(self, connection, module, service, changed=False): self._connection = connection self._module = module self._service = service self._changed = changed self._diff = {'after': dict(), 'before': dict()} @property def changed(self): return self._changed @changed.setter def changed(self, changed): if not self._changed: self._changed = changed @abstractmethod def build_entity(self): """ This method should return oVirt Python SDK type, which we want to create or update, initialized by values passed by Ansible module. For example if we want to create VM, we will return following: types.Vm(name=self._module.params['vm_name']) :return: Specific instance of sdk.Struct. """ pass def param(self, name, default=None): """ Return a module parameter specified by it's name. """ return self._module.params.get(name, default) def update_check(self, entity): """ This method handle checks whether the entity values are same as values passed to ansible module. By default we don't compare any values. :param entity: Entity we want to compare with Ansible module values. :return: True if values are same, so we don't need to update the entity. """ return True def pre_create(self, entity): """ This method is called right before entity is created. :param entity: Entity to be created or updated. """ pass def post_create(self, entity): """ This method is called right after entity is created. :param entity: Entity which was created. """ pass def post_update(self, entity): """ This method is called right after entity is updated. :param entity: Entity which was updated. """ pass def diff_update(self, after, update): for k, v in update.items(): if isinstance(v, Mapping): after[k] = self.diff_update(after.get(k, dict()), v) else: after[k] = update[k] return after def create( self, entity=None, result_state=None, fail_condition=lambda e: False, search_params=None, update_params=None, _wait=None, force_create=False, **kwargs ): """ Method which is called when state of the entity is 'present'. If user don't provide `entity` parameter the entity is searched using `search_params` parameter. If entity is found it's updated, whether the entity should be updated is checked by `update_check` method. The corresponding updated entity is build by `build_entity` method. Function executed after entity is created can optionally be specified in `post_create` parameter. Function executed after entity is updated can optionally be specified in `post_update` parameter. :param entity: Entity we want to update, if exists. :param result_state: State which should entity has in order to finish task. :param fail_condition: Function which checks incorrect state of entity, if it returns `True` Exception is raised. :param search_params: Dictionary of parameters to be used for search. :param update_params: The params which should be passed to update method. :param kwargs: Additional parameters passed when creating entity. :return: Dictionary with values returned by Ansible module. """ if entity is None and not force_create: entity = self.search_entity(search_params) self.pre_create(entity) if entity: # Entity exists, so update it: entity_service = self._service.service(entity.id) if not self.update_check(entity): new_entity = self.build_entity() if not self._module.check_mode: update_params = update_params or {} updated_entity = entity_service.update( new_entity, **update_params ) self.post_update(entity) # Update diffs only if user specified --diff parameter, # so we don't useless overload API: if self._module._diff: before = get_dict_of_struct( entity, self._connection, fetch_nested=True, attributes=['name'], ) after = before.copy() self.diff_update(after, get_dict_of_struct(new_entity)) self._diff['before'] = before self._diff['after'] = after self.changed = True else: # Entity don't exists, so create it: if not self._module.check_mode: entity = self._service.add( self.build_entity(), **kwargs ) self.post_create(entity) self.changed = True if not self._module.check_mode: # Wait for the entity to be created and to be in the defined state: entity_service = self._service.service(entity.id) def state_condition(entity): return entity if result_state: def state_condition(entity): return entity and entity.status == result_state wait( service=entity_service, condition=state_condition, fail_condition=fail_condition, wait=_wait if _wait is not None else self._module.params['wait'], timeout=self._module.params['timeout'], poll_interval=self._module.params['poll_interval'], ) return { 'changed': self.changed, 'id': getattr(entity, 'id', None), type(entity).__name__.lower(): get_dict_of_struct( struct=entity, connection=self._connection, fetch_nested=self._module.params.get('fetch_nested'), attributes=self._module.params.get('nested_attributes'), ), 'diff': self._diff, } def pre_remove(self, entity): """ This method is called right before entity is removed. :param entity: Entity which we want to remove. """ pass def entity_name(self, entity): return "{e_type} '{e_name}'".format( e_type=type(entity).__name__.lower(), e_name=getattr(entity, 'name', None), ) def remove(self, entity=None, search_params=None, **kwargs): """ Method which is called when state of the entity is 'absent'. If user don't provide `entity` parameter the entity is searched using `search_params` parameter. If entity is found it's removed. Function executed before remove is executed can optionally be specified in `pre_remove` parameter. :param entity: Entity we want to remove. :param search_params: Dictionary of parameters to be used for search. :param kwargs: Additional parameters passed when removing entity. :return: Dictionary with values returned by Ansible module. """ if entity is None: entity = self.search_entity(search_params) if entity is None: return { 'changed': self.changed, 'msg': "Entity wasn't found." } self.pre_remove(entity) entity_service = self._service.service(entity.id) if not self._module.check_mode: entity_service.remove(**kwargs) wait( service=entity_service, condition=lambda entity: not entity, wait=self._module.params['wait'], timeout=self._module.params['timeout'], poll_interval=self._module.params['poll_interval'], ) self.changed = True return { 'changed': self.changed, 'id': entity.id, type(entity).__name__.lower(): get_dict_of_struct( struct=entity, connection=self._connection, fetch_nested=self._module.params.get('fetch_nested'), attributes=self._module.params.get('nested_attributes'), ), } def action( self, action, entity=None, action_condition=lambda e: e, wait_condition=lambda e: e, fail_condition=lambda e: False, pre_action=lambda e: e, post_action=lambda e: None, search_params=None, **kwargs ): """ This method is executed when we want to change the state of some oVirt entity. The action to be executed on oVirt service is specified by `action` parameter. Whether the action should be executed can be specified by passing `action_condition` parameter. State which the entity should be in after execution of the action can be specified by `wait_condition` parameter. Function executed before an action on entity can optionally be specified in `pre_action` parameter. Function executed after an action on entity can optionally be specified in `post_action` parameter. :param action: Action which should be executed by service on entity. :param entity: Entity we want to run action on. :param action_condition: Function which is executed when checking if action should be executed. :param fail_condition: Function which checks incorrect state of entity, if it returns `True` Exception is raised. :param wait_condition: Function which is executed when waiting on result state. :param pre_action: Function which is executed before running the action. :param post_action: Function which is executed after running the action. :param search_params: Dictionary of parameters to be used for search. :param kwargs: Additional parameters passed to action. :return: Dictionary with values returned by Ansible module. """ if entity is None: entity = self.search_entity(search_params) entity = pre_action(entity) if entity is None: self._module.fail_json( msg="Entity not found, can't run action '{0}'.".format( action ) ) entity_service = self._service.service(entity.id) entity = entity_service.get() if action_condition(entity): if not self._module.check_mode: getattr(entity_service, action)(**kwargs) self.changed = True post_action(entity) wait( service=self._service.service(entity.id), condition=wait_condition, fail_condition=fail_condition, wait=self._module.params['wait'], timeout=self._module.params['timeout'], poll_interval=self._module.params['poll_interval'], ) return { 'changed': self.changed, 'id': entity.id, type(entity).__name__.lower(): get_dict_of_struct( struct=entity, connection=self._connection, fetch_nested=self._module.params.get('fetch_nested'), attributes=self._module.params.get('nested_attributes'), ), 'diff': self._diff, } def wait_for_import(self, condition=lambda e: True): if self._module.params['wait']: start = time.time() timeout = self._module.params['timeout'] poll_interval = self._module.params['poll_interval'] while time.time() < start + timeout: entity = self.search_entity() if entity and condition(entity): return entity time.sleep(poll_interval) def search_entity(self, search_params=None, list_params=None): """ Always first try to search by `ID`, if ID isn't specified, check if user constructed special search in `search_params`, if not search by `name`. """ entity = None if 'id' in self._module.params and self._module.params['id'] is not None: entity = get_entity(self._service.service(self._module.params['id']), get_params=list_params) elif search_params is not None: entity = search_by_attributes(self._service, list_params=list_params, **search_params) elif self._module.params.get('name') is not None: entity = search_by_attributes(self._service, list_params=list_params, name=self._module.params['name']) return entity def _get_major(self, full_version): if full_version is None or full_version == "": return None if isinstance(full_version, otypes.Version): return int(full_version.major) return int(full_version.split('.')[0]) def _get_minor(self, full_version): if full_version is None or full_version == "": return None if isinstance(full_version, otypes.Version): return int(full_version.minor) return int(full_version.split('.')[1]) def _sdk4_error_maybe(): """ Allow for ovirtsdk4 not being installed. """ if HAS_SDK: return sdk.Error return type(None) class OvirtRetry(CloudRetry): base_class = _sdk4_error_maybe() @staticmethod def status_code_from_exception(error): return error.code @staticmethod def found(response_code, catch_extra_error_codes=None): # This is a list of error codes to retry. retry_on = [ # HTTP status: Conflict 409, ] if catch_extra_error_codes: retry_on.extend(catch_extra_error_codes) return response_code in retry_on
closed
ansible/ansible
https://github.com/ansible/ansible
60,106
Template lookup start string breaks environment vars parsing
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When we create a playbook with environment variables defined from input variables, if one of the tasks in this playbooks use a template lookup plugin with a start/end string different from default, it also changes the start/end string used to parse the environment variable and breaks its parsing. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Template Lookup Plugin ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create the playbook presented below, also create an empty file called dummy.yaml.j2. Execute the playbook with `ansible-playbook playbook.yaml -e test_entry=lalala` <!--- Paste example playbooks or commands between quotes below --> ```yaml # Bug example - hosts: localhost gather_facts: false environment: TEST_ENV: "{{ test_entry }}" tasks: - name: Test 1 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 2 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 3 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" environment: TEST_ENV: "[% test_entry %]" register: output - debug: msg: "{{ output.stdout }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The expected result was that Debug 1 and 2 output the correct result "lalala" and Debug 3 output output "[% test_entry %]" as it is just a workaround to the bug. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> What happened was that debug 1 had the right output, debug 2 had the variable parsing broken by the lookup and debug 3 worked as a workaround to the issue, which should not be necessary. <!--- Paste verbatim command output between quotes --> ```paste below USER@USER-note:~/workspace/tf-infra$ansible-playbook -e test_entry=lalala playbooks/test.yaml -vvvv ansible-playbook 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible-playbook python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] No config file found; using defaults setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user yaml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user ini declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user toml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/local/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test.yaml *************************************************************************************************************************************************************** Positional arguments: playbooks/test.yaml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) extra_vars: (u'test_entry=lalala',) verbosity: 4 connection: smart timeout: 10 1 plays in playbooks/test.yaml PLAY [localhost] ****************************************************************************************************************************************************************** META: ran handlers TASK [Test 1] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:10 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" && echo ansible-tmp-1565035196.17-187587540004383="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpFL3AO6 TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002597", "end": "2019-08-05 16:59:56.387369", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.384772", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:14 ok: [localhost] => { "msg": "lalala" } TASK [Test 2] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:17 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" && echo ansible-tmp-1565035196.46-279367437516145="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpriIGjL TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV='"'"'{{ test_entry }}'"'"' /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002174", "end": "2019-08-05 16:59:56.551546", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.549372", "stderr": "", "stderr_lines": [], "stdout": "{{ test_entry }}", "stdout_lines": [ "{{ test_entry }}" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:21 ok: [localhost] => { "msg": "{{ test_entry }}" } TASK [Test 3] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:24 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" && echo ansible-tmp-1565035196.61-117891973732187="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpKaHwr_ TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002216", "end": "2019-08-05 16:59:56.713032", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.710816", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:30 ok: [localhost] => { "msg": "lalala" } META: ran handlers META: ran handlers PLAY RECAP ************************************************************************************************************************************************************************ localhost : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/60106
https://github.com/ansible/ansible/pull/60513
92d621202601ec8ac1aed020f6c338655d8a660d
cdb7ab61a0f23f98e7c01fc46ecb47c3fd078aec
2019-08-05T20:02:56Z
python
2019-10-25T14:51:57Z
changelogs/fragments/60106-templar-contextmanager.yml
closed
ansible/ansible
https://github.com/ansible/ansible
60,106
Template lookup start string breaks environment vars parsing
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When we create a playbook with environment variables defined from input variables, if one of the tasks in this playbooks use a template lookup plugin with a start/end string different from default, it also changes the start/end string used to parse the environment variable and breaks its parsing. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Template Lookup Plugin ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create the playbook presented below, also create an empty file called dummy.yaml.j2. Execute the playbook with `ansible-playbook playbook.yaml -e test_entry=lalala` <!--- Paste example playbooks or commands between quotes below --> ```yaml # Bug example - hosts: localhost gather_facts: false environment: TEST_ENV: "{{ test_entry }}" tasks: - name: Test 1 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 2 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 3 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" environment: TEST_ENV: "[% test_entry %]" register: output - debug: msg: "{{ output.stdout }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The expected result was that Debug 1 and 2 output the correct result "lalala" and Debug 3 output output "[% test_entry %]" as it is just a workaround to the bug. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> What happened was that debug 1 had the right output, debug 2 had the variable parsing broken by the lookup and debug 3 worked as a workaround to the issue, which should not be necessary. <!--- Paste verbatim command output between quotes --> ```paste below USER@USER-note:~/workspace/tf-infra$ansible-playbook -e test_entry=lalala playbooks/test.yaml -vvvv ansible-playbook 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible-playbook python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] No config file found; using defaults setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user yaml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user ini declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user toml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/local/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test.yaml *************************************************************************************************************************************************************** Positional arguments: playbooks/test.yaml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) extra_vars: (u'test_entry=lalala',) verbosity: 4 connection: smart timeout: 10 1 plays in playbooks/test.yaml PLAY [localhost] ****************************************************************************************************************************************************************** META: ran handlers TASK [Test 1] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:10 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" && echo ansible-tmp-1565035196.17-187587540004383="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpFL3AO6 TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002597", "end": "2019-08-05 16:59:56.387369", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.384772", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:14 ok: [localhost] => { "msg": "lalala" } TASK [Test 2] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:17 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" && echo ansible-tmp-1565035196.46-279367437516145="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpriIGjL TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV='"'"'{{ test_entry }}'"'"' /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002174", "end": "2019-08-05 16:59:56.551546", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.549372", "stderr": "", "stderr_lines": [], "stdout": "{{ test_entry }}", "stdout_lines": [ "{{ test_entry }}" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:21 ok: [localhost] => { "msg": "{{ test_entry }}" } TASK [Test 3] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:24 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" && echo ansible-tmp-1565035196.61-117891973732187="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpKaHwr_ TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002216", "end": "2019-08-05 16:59:56.713032", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.710816", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:30 ok: [localhost] => { "msg": "lalala" } META: ran handlers META: ran handlers PLAY RECAP ************************************************************************************************************************************************************************ localhost : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/60106
https://github.com/ansible/ansible/pull/60513
92d621202601ec8ac1aed020f6c338655d8a660d
cdb7ab61a0f23f98e7c01fc46ecb47c3fd078aec
2019-08-05T20:02:56Z
python
2019-10-25T14:51:57Z
lib/ansible/plugins/action/ce_template.py
# # Copyright 2015 Peter Sprygada <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import time import glob from ansible.module_utils.six.moves.urllib.parse import urlsplit from ansible.module_utils._text import to_text from ansible.plugins.action.ce import ActionModule as _ActionModule class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None): try: self._handle_template() except (ValueError, AttributeError) as exc: return dict(failed=True, msg=exc.message) result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect if self._task.args.get('backup') and result.get('__backup__'): # User requested backup and no error occurred in module. # NOTE: If there is a parameter error, __backup__ key may not be in results. self._write_backup(task_vars['inventory_hostname'], result['__backup__']) if '__backup__' in result: del result['__backup__'] return result def _get_working_path(self): cwd = self._loader.get_basedir() if self._task._role is not None: cwd = self._task._role._role_path return cwd def _write_backup(self, host, contents): backup_path = self._get_working_path() + '/backup' if not os.path.exists(backup_path): os.mkdir(backup_path) for fn in glob.glob('%s/%s*' % (backup_path, host)): os.remove(fn) tstamp = time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime(time.time())) filename = '%s/%s_config.%s' % (backup_path, host, tstamp) open(filename, 'w').write(contents) def _handle_template(self): src = self._task.args.get('src') if not src: raise ValueError('missing required arguments: src') working_path = self._get_working_path() if os.path.isabs(src) or urlsplit(src).scheme: source = src else: source = self._loader.path_dwim_relative(working_path, 'templates', src) if not source: source = self._loader.path_dwim_relative(working_path, src) if not os.path.exists(source): return try: with open(source, 'r') as f: template_data = to_text(f.read()) except IOError: return dict(failed=True, msg='unable to load src file') # Create a template search path in the following order: # [working_path, self_role_path, dependent_role_paths, dirname(source)] searchpath = [working_path] if self._task._role is not None: searchpath.append(self._task._role._role_path) if hasattr(self._task, "_block:"): dep_chain = self._task._block.get_dep_chain() if dep_chain is not None: for role in dep_chain: searchpath.append(role._role_path) searchpath.append(os.path.dirname(source)) self._templar.environment.loader.searchpath = searchpath self._task.args['src'] = self._templar.template(template_data)
closed
ansible/ansible
https://github.com/ansible/ansible
60,106
Template lookup start string breaks environment vars parsing
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When we create a playbook with environment variables defined from input variables, if one of the tasks in this playbooks use a template lookup plugin with a start/end string different from default, it also changes the start/end string used to parse the environment variable and breaks its parsing. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Template Lookup Plugin ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create the playbook presented below, also create an empty file called dummy.yaml.j2. Execute the playbook with `ansible-playbook playbook.yaml -e test_entry=lalala` <!--- Paste example playbooks or commands between quotes below --> ```yaml # Bug example - hosts: localhost gather_facts: false environment: TEST_ENV: "{{ test_entry }}" tasks: - name: Test 1 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 2 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 3 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" environment: TEST_ENV: "[% test_entry %]" register: output - debug: msg: "{{ output.stdout }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The expected result was that Debug 1 and 2 output the correct result "lalala" and Debug 3 output output "[% test_entry %]" as it is just a workaround to the bug. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> What happened was that debug 1 had the right output, debug 2 had the variable parsing broken by the lookup and debug 3 worked as a workaround to the issue, which should not be necessary. <!--- Paste verbatim command output between quotes --> ```paste below USER@USER-note:~/workspace/tf-infra$ansible-playbook -e test_entry=lalala playbooks/test.yaml -vvvv ansible-playbook 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible-playbook python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] No config file found; using defaults setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user yaml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user ini declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user toml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/local/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test.yaml *************************************************************************************************************************************************************** Positional arguments: playbooks/test.yaml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) extra_vars: (u'test_entry=lalala',) verbosity: 4 connection: smart timeout: 10 1 plays in playbooks/test.yaml PLAY [localhost] ****************************************************************************************************************************************************************** META: ran handlers TASK [Test 1] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:10 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" && echo ansible-tmp-1565035196.17-187587540004383="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpFL3AO6 TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002597", "end": "2019-08-05 16:59:56.387369", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.384772", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:14 ok: [localhost] => { "msg": "lalala" } TASK [Test 2] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:17 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" && echo ansible-tmp-1565035196.46-279367437516145="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpriIGjL TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV='"'"'{{ test_entry }}'"'"' /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002174", "end": "2019-08-05 16:59:56.551546", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.549372", "stderr": "", "stderr_lines": [], "stdout": "{{ test_entry }}", "stdout_lines": [ "{{ test_entry }}" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:21 ok: [localhost] => { "msg": "{{ test_entry }}" } TASK [Test 3] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:24 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" && echo ansible-tmp-1565035196.61-117891973732187="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpKaHwr_ TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002216", "end": "2019-08-05 16:59:56.713032", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.710816", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:30 ok: [localhost] => { "msg": "lalala" } META: ran handlers META: ran handlers PLAY RECAP ************************************************************************************************************************************************************************ localhost : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/60106
https://github.com/ansible/ansible/pull/60513
92d621202601ec8ac1aed020f6c338655d8a660d
cdb7ab61a0f23f98e7c01fc46ecb47c3fd078aec
2019-08-05T20:02:56Z
python
2019-10-25T14:51:57Z
lib/ansible/plugins/action/network.py
# # (c) 2018 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import time import glob import re from ansible.errors import AnsibleError from ansible.module_utils._text import to_text, to_bytes from ansible.module_utils.six.moves.urllib.parse import urlsplit from ansible.plugins.action.normal import ActionModule as _ActionModule from ansible.utils.display import Display display = Display() PRIVATE_KEYS_RE = re.compile('__.+__') class ActionModule(_ActionModule): def run(self, task_vars=None): config_module = hasattr(self, '_config_module') and self._config_module if config_module and self._task.args.get('src'): try: self._handle_src_option() except AnsibleError as e: return {'failed': True, 'msg': e.message, 'changed': False} result = super(ActionModule, self).run(task_vars=task_vars) if config_module and self._task.args.get('backup') and not result.get('failed'): self._handle_backup_option(result, task_vars) return result def _handle_backup_option(self, result, task_vars): filename = None backup_path = None try: content = result['__backup__'] except KeyError: raise AnsibleError('Failed while reading configuration backup') backup_options = self._task.args.get('backup_options') if backup_options: filename = backup_options.get('filename') backup_path = backup_options.get('dir_path') if not backup_path: cwd = self._get_working_path() backup_path = os.path.join(cwd, 'backup') if not filename: tstamp = time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime(time.time())) filename = '%s_config.%s' % (task_vars['inventory_hostname'], tstamp) dest = os.path.join(backup_path, filename) backup_path = os.path.expanduser(os.path.expandvars(to_bytes(backup_path, errors='surrogate_or_strict'))) if not os.path.exists(backup_path): os.makedirs(backup_path) new_task = self._task.copy() for item in self._task.args: if not item.startswith('_'): new_task.args.pop(item, None) new_task.args.update( dict( content=content, dest=dest, ), ) copy_action = self._shared_loader_obj.action_loader.get('copy', task=new_task, connection=self._connection, play_context=self._play_context, loader=self._loader, templar=self._templar, shared_loader_obj=self._shared_loader_obj) copy_result = copy_action.run(task_vars=task_vars) if copy_result.get('failed'): result['failed'] = copy_result['failed'] result['msg'] = copy_result.get('msg') return result['backup_path'] = dest if copy_result.get('changed', False): result['changed'] = copy_result['changed'] if backup_options and backup_options.get('filename'): result['date'] = time.strftime('%Y-%m-%d', time.gmtime(os.stat(result['backup_path']).st_ctime)) result['time'] = time.strftime('%H:%M:%S', time.gmtime(os.stat(result['backup_path']).st_ctime)) else: result['date'] = tstamp.split('@')[0] result['time'] = tstamp.split('@')[1] result['shortname'] = result['backup_path'][::-1].split('.', 1)[1][::-1] result['filename'] = result['backup_path'].split('/')[-1] # strip out any keys that have two leading and two trailing # underscore characters for key in list(result.keys()): if PRIVATE_KEYS_RE.match(key): del result[key] def _get_working_path(self): cwd = self._loader.get_basedir() if self._task._role is not None: cwd = self._task._role._role_path return cwd def _handle_src_option(self, convert_data=True): src = self._task.args.get('src') working_path = self._get_working_path() if os.path.isabs(src) or urlsplit('src').scheme: source = src else: source = self._loader.path_dwim_relative(working_path, 'templates', src) if not source: source = self._loader.path_dwim_relative(working_path, src) if not os.path.exists(source): raise AnsibleError('path specified in src not found') try: with open(source, 'r') as f: template_data = to_text(f.read()) except IOError as e: raise AnsibleError("unable to load src file {0}, I/O error({1}): {2}".format(source, e.errno, e.strerror)) # Create a template search path in the following order: # [working_path, self_role_path, dependent_role_paths, dirname(source)] searchpath = [working_path] if self._task._role is not None: searchpath.append(self._task._role._role_path) if hasattr(self._task, "_block:"): dep_chain = self._task._block.get_dep_chain() if dep_chain is not None: for role in dep_chain: searchpath.append(role._role_path) searchpath.append(os.path.dirname(source)) self._templar.environment.loader.searchpath = searchpath self._task.args['src'] = self._templar.template(template_data, convert_data=convert_data) def _get_network_os(self, task_vars): if 'network_os' in self._task.args and self._task.args['network_os']: display.vvvv('Getting network OS from task argument') network_os = self._task.args['network_os'] elif self._play_context.network_os: display.vvvv('Getting network OS from inventory') network_os = self._play_context.network_os elif 'network_os' in task_vars.get('ansible_facts', {}) and task_vars['ansible_facts']['network_os']: display.vvvv('Getting network OS from fact') network_os = task_vars['ansible_facts']['network_os'] else: raise AnsibleError('ansible_network_os must be specified on this host') return network_os
closed
ansible/ansible
https://github.com/ansible/ansible
60,106
Template lookup start string breaks environment vars parsing
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When we create a playbook with environment variables defined from input variables, if one of the tasks in this playbooks use a template lookup plugin with a start/end string different from default, it also changes the start/end string used to parse the environment variable and breaks its parsing. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Template Lookup Plugin ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create the playbook presented below, also create an empty file called dummy.yaml.j2. Execute the playbook with `ansible-playbook playbook.yaml -e test_entry=lalala` <!--- Paste example playbooks or commands between quotes below --> ```yaml # Bug example - hosts: localhost gather_facts: false environment: TEST_ENV: "{{ test_entry }}" tasks: - name: Test 1 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 2 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 3 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" environment: TEST_ENV: "[% test_entry %]" register: output - debug: msg: "{{ output.stdout }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The expected result was that Debug 1 and 2 output the correct result "lalala" and Debug 3 output output "[% test_entry %]" as it is just a workaround to the bug. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> What happened was that debug 1 had the right output, debug 2 had the variable parsing broken by the lookup and debug 3 worked as a workaround to the issue, which should not be necessary. <!--- Paste verbatim command output between quotes --> ```paste below USER@USER-note:~/workspace/tf-infra$ansible-playbook -e test_entry=lalala playbooks/test.yaml -vvvv ansible-playbook 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible-playbook python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] No config file found; using defaults setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user yaml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user ini declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user toml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/local/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test.yaml *************************************************************************************************************************************************************** Positional arguments: playbooks/test.yaml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) extra_vars: (u'test_entry=lalala',) verbosity: 4 connection: smart timeout: 10 1 plays in playbooks/test.yaml PLAY [localhost] ****************************************************************************************************************************************************************** META: ran handlers TASK [Test 1] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:10 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" && echo ansible-tmp-1565035196.17-187587540004383="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpFL3AO6 TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002597", "end": "2019-08-05 16:59:56.387369", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.384772", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:14 ok: [localhost] => { "msg": "lalala" } TASK [Test 2] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:17 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" && echo ansible-tmp-1565035196.46-279367437516145="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpriIGjL TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV='"'"'{{ test_entry }}'"'"' /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002174", "end": "2019-08-05 16:59:56.551546", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.549372", "stderr": "", "stderr_lines": [], "stdout": "{{ test_entry }}", "stdout_lines": [ "{{ test_entry }}" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:21 ok: [localhost] => { "msg": "{{ test_entry }}" } TASK [Test 3] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:24 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" && echo ansible-tmp-1565035196.61-117891973732187="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpKaHwr_ TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002216", "end": "2019-08-05 16:59:56.713032", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.710816", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:30 ok: [localhost] => { "msg": "lalala" } META: ran handlers META: ran handlers PLAY RECAP ************************************************************************************************************************************************************************ localhost : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/60106
https://github.com/ansible/ansible/pull/60513
92d621202601ec8ac1aed020f6c338655d8a660d
cdb7ab61a0f23f98e7c01fc46ecb47c3fd078aec
2019-08-05T20:02:56Z
python
2019-10-25T14:51:57Z
lib/ansible/plugins/action/template.py
# Copyright: (c) 2015, Michael DeHaan <[email protected]> # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import shutil import stat import tempfile from ansible import constants as C from ansible.config.manager import ensure_type from ansible.errors import AnsibleError, AnsibleFileNotFound, AnsibleAction, AnsibleActionFail from ansible.module_utils._text import to_bytes, to_text, to_native from ansible.module_utils.parsing.convert_bool import boolean from ansible.module_utils.six import string_types from ansible.plugins.action import ActionBase from ansible.template import generate_ansible_template_vars class ActionModule(ActionBase): TRANSFERS_FILES = True DEFAULT_NEWLINE_SEQUENCE = "\n" def run(self, tmp=None, task_vars=None): ''' handler for template operations ''' if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect # Options type validation # stings for s_type in ('src', 'dest', 'state', 'newline_sequence', 'variable_start_string', 'variable_end_string', 'block_start_string', 'block_end_string'): if s_type in self._task.args: value = ensure_type(self._task.args[s_type], 'string') if value is not None and not isinstance(value, string_types): raise AnsibleActionFail("%s is expected to be a string, but got %s instead" % (s_type, type(value))) self._task.args[s_type] = value # booleans try: follow = boolean(self._task.args.get('follow', False), strict=False) trim_blocks = boolean(self._task.args.get('trim_blocks', True), strict=False) lstrip_blocks = boolean(self._task.args.get('lstrip_blocks', False), strict=False) except TypeError as e: raise AnsibleActionFail(to_native(e)) # assign to local vars for ease of use source = self._task.args.get('src', None) dest = self._task.args.get('dest', None) state = self._task.args.get('state', None) newline_sequence = self._task.args.get('newline_sequence', self.DEFAULT_NEWLINE_SEQUENCE) variable_start_string = self._task.args.get('variable_start_string', None) variable_end_string = self._task.args.get('variable_end_string', None) block_start_string = self._task.args.get('block_start_string', None) block_end_string = self._task.args.get('block_end_string', None) output_encoding = self._task.args.get('output_encoding', 'utf-8') or 'utf-8' # Option `lstrip_blocks' was added in Jinja2 version 2.7. if lstrip_blocks: try: import jinja2.defaults except ImportError: raise AnsibleError('Unable to import Jinja2 defaults for determining Jinja2 features.') try: jinja2.defaults.LSTRIP_BLOCKS except AttributeError: raise AnsibleError("Option `lstrip_blocks' is only available in Jinja2 versions >=2.7") wrong_sequences = ["\\n", "\\r", "\\r\\n"] allowed_sequences = ["\n", "\r", "\r\n"] # We need to convert unescaped sequences to proper escaped sequences for Jinja2 if newline_sequence in wrong_sequences: newline_sequence = allowed_sequences[wrong_sequences.index(newline_sequence)] try: # logical validation if state is not None: raise AnsibleActionFail("'state' cannot be specified on a template") elif source is None or dest is None: raise AnsibleActionFail("src and dest are required") elif newline_sequence not in allowed_sequences: raise AnsibleActionFail("newline_sequence needs to be one of: \n, \r or \r\n") else: try: source = self._find_needle('templates', source) except AnsibleError as e: raise AnsibleActionFail(to_text(e)) mode = self._task.args.get('mode', None) if mode == 'preserve': mode = '0%03o' % stat.S_IMODE(os.stat(source).st_mode) # Get vault decrypted tmp file try: tmp_source = self._loader.get_real_file(source) except AnsibleFileNotFound as e: raise AnsibleActionFail("could not find src=%s, %s" % (source, to_text(e))) b_tmp_source = to_bytes(tmp_source, errors='surrogate_or_strict') # template the source data locally & get ready to transfer try: with open(b_tmp_source, 'rb') as f: try: template_data = to_text(f.read(), errors='surrogate_or_strict') except UnicodeError: raise AnsibleActionFail("Template source files must be utf-8 encoded") # set jinja2 internal search path for includes searchpath = task_vars.get('ansible_search_path', []) searchpath.extend([self._loader._basedir, os.path.dirname(source)]) # We want to search into the 'templates' subdir of each search path in # addition to our original search paths. newsearchpath = [] for p in searchpath: newsearchpath.append(os.path.join(p, 'templates')) newsearchpath.append(p) searchpath = newsearchpath self._templar.environment.loader.searchpath = searchpath self._templar.environment.newline_sequence = newline_sequence if block_start_string is not None: self._templar.environment.block_start_string = block_start_string if block_end_string is not None: self._templar.environment.block_end_string = block_end_string if variable_start_string is not None: self._templar.environment.variable_start_string = variable_start_string if variable_end_string is not None: self._templar.environment.variable_end_string = variable_end_string self._templar.environment.trim_blocks = trim_blocks self._templar.environment.lstrip_blocks = lstrip_blocks # add ansible 'template' vars temp_vars = task_vars.copy() temp_vars.update(generate_ansible_template_vars(source, dest)) old_vars = self._templar.available_variables self._templar.available_variables = temp_vars resultant = self._templar.do_template(template_data, preserve_trailing_newlines=True, escape_backslashes=False) self._templar.available_variables = old_vars except AnsibleAction: raise except Exception as e: raise AnsibleActionFail("%s: %s" % (type(e).__name__, to_text(e))) finally: self._loader.cleanup_tmp_file(b_tmp_source) new_task = self._task.copy() # mode is either the mode from task.args or the mode of the source file if the task.args # mode == 'preserve' new_task.args['mode'] = mode # remove 'template only' options: for remove in ('newline_sequence', 'block_start_string', 'block_end_string', 'variable_start_string', 'variable_end_string', 'trim_blocks', 'lstrip_blocks', 'output_encoding'): new_task.args.pop(remove, None) local_tempdir = tempfile.mkdtemp(dir=C.DEFAULT_LOCAL_TMP) try: result_file = os.path.join(local_tempdir, os.path.basename(source)) with open(to_bytes(result_file, errors='surrogate_or_strict'), 'wb') as f: f.write(to_bytes(resultant, encoding=output_encoding, errors='surrogate_or_strict')) new_task.args.update( dict( src=result_file, dest=dest, follow=follow, ), ) copy_action = self._shared_loader_obj.action_loader.get('copy', task=new_task, connection=self._connection, play_context=self._play_context, loader=self._loader, templar=self._templar, shared_loader_obj=self._shared_loader_obj) result.update(copy_action.run(task_vars=task_vars)) finally: shutil.rmtree(to_bytes(local_tempdir, errors='surrogate_or_strict')) except AnsibleAction as e: result.update(e.result) finally: self._remove_tmp_path(self._connection._shell.tmpdir) return result
closed
ansible/ansible
https://github.com/ansible/ansible
60,106
Template lookup start string breaks environment vars parsing
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When we create a playbook with environment variables defined from input variables, if one of the tasks in this playbooks use a template lookup plugin with a start/end string different from default, it also changes the start/end string used to parse the environment variable and breaks its parsing. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Template Lookup Plugin ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create the playbook presented below, also create an empty file called dummy.yaml.j2. Execute the playbook with `ansible-playbook playbook.yaml -e test_entry=lalala` <!--- Paste example playbooks or commands between quotes below --> ```yaml # Bug example - hosts: localhost gather_facts: false environment: TEST_ENV: "{{ test_entry }}" tasks: - name: Test 1 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 2 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 3 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" environment: TEST_ENV: "[% test_entry %]" register: output - debug: msg: "{{ output.stdout }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The expected result was that Debug 1 and 2 output the correct result "lalala" and Debug 3 output output "[% test_entry %]" as it is just a workaround to the bug. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> What happened was that debug 1 had the right output, debug 2 had the variable parsing broken by the lookup and debug 3 worked as a workaround to the issue, which should not be necessary. <!--- Paste verbatim command output between quotes --> ```paste below USER@USER-note:~/workspace/tf-infra$ansible-playbook -e test_entry=lalala playbooks/test.yaml -vvvv ansible-playbook 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible-playbook python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] No config file found; using defaults setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user yaml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user ini declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user toml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/local/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test.yaml *************************************************************************************************************************************************************** Positional arguments: playbooks/test.yaml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) extra_vars: (u'test_entry=lalala',) verbosity: 4 connection: smart timeout: 10 1 plays in playbooks/test.yaml PLAY [localhost] ****************************************************************************************************************************************************************** META: ran handlers TASK [Test 1] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:10 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" && echo ansible-tmp-1565035196.17-187587540004383="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpFL3AO6 TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002597", "end": "2019-08-05 16:59:56.387369", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.384772", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:14 ok: [localhost] => { "msg": "lalala" } TASK [Test 2] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:17 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" && echo ansible-tmp-1565035196.46-279367437516145="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpriIGjL TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV='"'"'{{ test_entry }}'"'"' /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002174", "end": "2019-08-05 16:59:56.551546", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.549372", "stderr": "", "stderr_lines": [], "stdout": "{{ test_entry }}", "stdout_lines": [ "{{ test_entry }}" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:21 ok: [localhost] => { "msg": "{{ test_entry }}" } TASK [Test 3] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:24 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" && echo ansible-tmp-1565035196.61-117891973732187="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpKaHwr_ TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002216", "end": "2019-08-05 16:59:56.713032", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.710816", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:30 ok: [localhost] => { "msg": "lalala" } META: ran handlers META: ran handlers PLAY RECAP ************************************************************************************************************************************************************************ localhost : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/60106
https://github.com/ansible/ansible/pull/60513
92d621202601ec8ac1aed020f6c338655d8a660d
cdb7ab61a0f23f98e7c01fc46ecb47c3fd078aec
2019-08-05T20:02:56Z
python
2019-10-25T14:51:57Z
lib/ansible/plugins/lookup/template.py
# Copyright: (c) 2012, Michael DeHaan <[email protected]> # Copyright: (c) 2012-17, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ lookup: template author: Michael DeHaan <[email protected]> version_added: "0.9" short_description: retrieve contents of file after templating with Jinja2 description: - Returns a list of strings; for each template in the list of templates you pass in, returns a string containing the results of processing that template. options: _terms: description: list of files to template convert_data: type: bool description: whether to convert YAML into data. If False, strings that are YAML will be left untouched. variable_start_string: description: The string marking the beginning of a print statement. default: '{{' version_added: '2.8' type: str variable_end_string: description: The string marking the end of a print statement. default: '}}' version_added: '2.8' type: str """ EXAMPLES = """ - name: show templating results debug: msg: "{{ lookup('template', './some_template.j2') }}" - name: show templating results with different variable start and end string debug: msg: "{{ lookup('template', './some_template.j2', variable_start_string='[%', variable_end_string='%]') }}" """ RETURN = """ _raw: description: file(s) content after templating """ from copy import deepcopy import os from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from ansible.module_utils._text import to_bytes, to_text from ansible.template import generate_ansible_template_vars from ansible.utils.display import Display display = Display() class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): convert_data_p = kwargs.get('convert_data', True) lookup_template_vars = kwargs.get('template_vars', {}) ret = [] variable_start_string = kwargs.get('variable_start_string', None) variable_end_string = kwargs.get('variable_end_string', None) old_vars = self._templar.available_variables for term in terms: display.debug("File lookup term: %s" % term) lookupfile = self.find_file_in_search_path(variables, 'templates', term) display.vvvv("File lookup using %s as file" % lookupfile) if lookupfile: b_template_data, show_data = self._loader._get_file_contents(lookupfile) template_data = to_text(b_template_data, errors='surrogate_or_strict') # set jinja2 internal search path for includes searchpath = variables.get('ansible_search_path', []) if searchpath: # our search paths aren't actually the proper ones for jinja includes. # We want to search into the 'templates' subdir of each search path in # addition to our original search paths. newsearchpath = [] for p in searchpath: newsearchpath.append(os.path.join(p, 'templates')) newsearchpath.append(p) searchpath = newsearchpath searchpath.insert(0, os.path.dirname(lookupfile)) self._templar.environment.loader.searchpath = searchpath if variable_start_string is not None: self._templar.environment.variable_start_string = variable_start_string if variable_end_string is not None: self._templar.environment.variable_end_string = variable_end_string # The template will have access to all existing variables, # plus some added by ansible (e.g., template_{path,mtime}), # plus anything passed to the lookup with the template_vars= # argument. vars = deepcopy(variables) vars.update(generate_ansible_template_vars(lookupfile)) vars.update(lookup_template_vars) self._templar.available_variables = vars # do the templating res = self._templar.template(template_data, preserve_trailing_newlines=True, convert_data=convert_data_p, escape_backslashes=False) ret.append(res) else: raise AnsibleError("the template file %s could not be found for the lookup" % term) # restore old variables self._templar.available_variables = old_vars return ret
closed
ansible/ansible
https://github.com/ansible/ansible
60,106
Template lookup start string breaks environment vars parsing
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When we create a playbook with environment variables defined from input variables, if one of the tasks in this playbooks use a template lookup plugin with a start/end string different from default, it also changes the start/end string used to parse the environment variable and breaks its parsing. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> Template Lookup Plugin ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Create the playbook presented below, also create an empty file called dummy.yaml.j2. Execute the playbook with `ansible-playbook playbook.yaml -e test_entry=lalala` <!--- Paste example playbooks or commands between quotes below --> ```yaml # Bug example - hosts: localhost gather_facts: false environment: TEST_ENV: "{{ test_entry }}" tasks: - name: Test 1 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 2 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" register: output - debug: msg: "{{ output.stdout }}" - name: Test 3 command: "echo ${TEST_ENV} {{ lookup('template', 'dummy.yaml.j2', variable_start_string='[%', variable_end_string='%]') }}" environment: TEST_ENV: "[% test_entry %]" register: output - debug: msg: "{{ output.stdout }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The expected result was that Debug 1 and 2 output the correct result "lalala" and Debug 3 output output "[% test_entry %]" as it is just a workaround to the bug. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> What happened was that debug 1 had the right output, debug 2 had the variable parsing broken by the lookup and debug 3 worked as a workaround to the issue, which should not be necessary. <!--- Paste verbatim command output between quotes --> ```paste below USER@USER-note:~/workspace/tf-infra$ansible-playbook -e test_entry=lalala playbooks/test.yaml -vvvv ansible-playbook 2.8.3 config file = None configured module search path = [u'/home/USER/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible-playbook python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0] No config file found; using defaults setting up inventory plugins host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user yaml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user ini declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Skipping due to inventory source not existing or not being readable by the current user toml declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Loading callback plugin default of type stdout, v2.0 from /usr/local/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc PLAYBOOK: test.yaml *************************************************************************************************************************************************************** Positional arguments: playbooks/test.yaml become_method: sudo inventory: (u'/etc/ansible/hosts',) forks: 5 tags: (u'all',) extra_vars: (u'test_entry=lalala',) verbosity: 4 connection: smart timeout: 10 1 plays in playbooks/test.yaml PLAY [localhost] ****************************************************************************************************************************************************************** META: ran handlers TASK [Test 1] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:10 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" && echo ansible-tmp-1565035196.17-187587540004383="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpFL3AO6 TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.17-187587540004383/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002597", "end": "2019-08-05 16:59:56.387369", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.384772", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:14 ok: [localhost] => { "msg": "lalala" } TASK [Test 2] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:17 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" && echo ansible-tmp-1565035196.46-279367437516145="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpriIGjL TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV='"'"'{{ test_entry }}'"'"' /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.46-279367437516145/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002174", "end": "2019-08-05 16:59:56.551546", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.549372", "stderr": "", "stderr_lines": [], "stdout": "{{ test_entry }}", "stdout_lines": [ "{{ test_entry }}" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:21 ok: [localhost] => { "msg": "{{ test_entry }}" } TASK [Test 3] ********************************************************************************************************************************************************************* task path: /home/USER/workspace/playbooks/test.yaml:24 File lookup using /home/USER/workspace/playbooks/dummy.yaml.j2 as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: USER <127.0.0.1> EXEC /bin/sh -c 'echo ~USER && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" && echo ansible-tmp-1565035196.61-117891973732187="` echo /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187 `" ) && sleep 0' Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/commands/command.py <127.0.0.1> PUT /home/USER/.ansible/tmp/ansible-local-299637oQZ14/tmpKaHwr_ TO /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'TEST_ENV=lalala /usr/bin/python /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/AnsiballZ_command.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/USER/.ansible/tmp/ansible-tmp-1565035196.61-117891973732187/ > /dev/null 2>&1 && sleep 0' changed: [localhost] => { "changed": true, "cmd": [ "echo", "${TEST_ENV}" ], "delta": "0:00:00.002216", "end": "2019-08-05 16:59:56.713032", "invocation": { "module_args": { "_raw_params": "echo ${TEST_ENV} ", "_uses_shell": false, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "stdin_add_newline": true, "strip_empty_ends": true, "warn": true } }, "rc": 0, "start": "2019-08-05 16:59:56.710816", "stderr": "", "stderr_lines": [], "stdout": "lalala", "stdout_lines": [ "lalala" ] } TASK [debug] ********************************************************************************************************************************************************************** task path: /home/USER/workspace/playbooks/test.yaml:30 ok: [localhost] => { "msg": "lalala" } META: ran handlers META: ran handlers PLAY RECAP ************************************************************************************************************************************************************************ localhost : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/60106
https://github.com/ansible/ansible/pull/60513
92d621202601ec8ac1aed020f6c338655d8a660d
cdb7ab61a0f23f98e7c01fc46ecb47c3fd078aec
2019-08-05T20:02:56Z
python
2019-10-25T14:51:57Z
lib/ansible/template/__init__.py
# (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import ast import datetime import os import pkgutil import pwd import re import time from numbers import Number try: from hashlib import sha1 except ImportError: from sha import sha as sha1 from jinja2.exceptions import TemplateSyntaxError, UndefinedError from jinja2.loaders import FileSystemLoader from jinja2.runtime import Context, StrictUndefined from ansible import constants as C from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleUndefinedVariable, AnsibleAssertionError from ansible.module_utils.six import iteritems, string_types, text_type from ansible.module_utils._text import to_native, to_text, to_bytes from ansible.module_utils.common._collections_compat import Sequence, Mapping, MutableMapping from ansible.plugins.loader import filter_loader, lookup_loader, test_loader from ansible.template.safe_eval import safe_eval from ansible.template.template import AnsibleJ2Template from ansible.template.vars import AnsibleJ2Vars from ansible.utils.collection_loader import AnsibleCollectionRef from ansible.utils.display import Display from ansible.utils.unsafe_proxy import wrap_var # HACK: keep Python 2.6 controller tests happy in CI until they're properly split try: from importlib import import_module except ImportError: import_module = __import__ display = Display() __all__ = ['Templar', 'generate_ansible_template_vars'] # A regex for checking to see if a variable we're trying to # expand is just a single variable name. # Primitive Types which we don't want Jinja to convert to strings. NON_TEMPLATED_TYPES = (bool, Number) JINJA2_OVERRIDE = '#jinja2:' USE_JINJA2_NATIVE = False if C.DEFAULT_JINJA2_NATIVE: try: from jinja2.nativetypes import NativeEnvironment as Environment from ansible.template.native_helpers import ansible_native_concat as j2_concat USE_JINJA2_NATIVE = True except ImportError: from jinja2 import Environment from jinja2.utils import concat as j2_concat from jinja2 import __version__ as j2_version display.warning( 'jinja2_native requires Jinja 2.10 and above. ' 'Version detected: %s. Falling back to default.' % j2_version ) else: from jinja2 import Environment from jinja2.utils import concat as j2_concat JINJA2_BEGIN_TOKENS = frozenset(('variable_begin', 'block_begin', 'comment_begin', 'raw_begin')) JINJA2_END_TOKENS = frozenset(('variable_end', 'block_end', 'comment_end', 'raw_end')) def generate_ansible_template_vars(path, dest_path=None): b_path = to_bytes(path) try: template_uid = pwd.getpwuid(os.stat(b_path).st_uid).pw_name except (KeyError, TypeError): template_uid = os.stat(b_path).st_uid temp_vars = { 'template_host': to_text(os.uname()[1]), 'template_path': path, 'template_mtime': datetime.datetime.fromtimestamp(os.path.getmtime(b_path)), 'template_uid': to_text(template_uid), 'template_fullpath': os.path.abspath(path), 'template_run_date': datetime.datetime.now(), 'template_destpath': to_native(dest_path) if dest_path else None, } managed_default = C.DEFAULT_MANAGED_STR managed_str = managed_default.format( host=temp_vars['template_host'], uid=temp_vars['template_uid'], file=temp_vars['template_path'], ) temp_vars['ansible_managed'] = to_text(time.strftime(to_native(managed_str), time.localtime(os.path.getmtime(b_path)))) return temp_vars def _escape_backslashes(data, jinja_env): """Double backslashes within jinja2 expressions A user may enter something like this in a playbook:: debug: msg: "Test Case 1\\3; {{ test1_name | regex_replace('^(.*)_name$', '\\1')}}" The string inside of the {{ gets interpreted multiple times First by yaml. Then by python. And finally by jinja2 as part of it's variable. Because it is processed by both python and jinja2, the backslash escaped characters get unescaped twice. This means that we'd normally have to use four backslashes to escape that. This is painful for playbook authors as they have to remember different rules for inside vs outside of a jinja2 expression (The backslashes outside of the "{{ }}" only get processed by yaml and python. So they only need to be escaped once). The following code fixes this by automatically performing the extra quoting of backslashes inside of a jinja2 expression. """ if '\\' in data and '{{' in data: new_data = [] d2 = jinja_env.preprocess(data) in_var = False for token in jinja_env.lex(d2): if token[1] == 'variable_begin': in_var = True new_data.append(token[2]) elif token[1] == 'variable_end': in_var = False new_data.append(token[2]) elif in_var and token[1] == 'string': # Double backslashes only if we're inside of a jinja2 variable new_data.append(token[2].replace('\\', '\\\\')) else: new_data.append(token[2]) data = ''.join(new_data) return data def is_template(data, jinja_env): """This function attempts to quickly detect whether a value is a jinja2 template. To do so, we look for the first 2 matching jinja2 tokens for start and end delimiters. """ found = None start = True comment = False d2 = jinja_env.preprocess(data) # This wraps a lot of code, but this is due to lex returing a generator # so we may get an exception at any part of the loop try: for token in jinja_env.lex(d2): if token[1] in JINJA2_BEGIN_TOKENS: if start and token[1] == 'comment_begin': # Comments can wrap other token types comment = True start = False # Example: variable_end -> variable found = token[1].split('_')[0] elif token[1] in JINJA2_END_TOKENS: if token[1].split('_')[0] == found: return True elif comment: continue return False except TemplateSyntaxError: return False return False def _count_newlines_from_end(in_str): ''' Counts the number of newlines at the end of a string. This is used during the jinja2 templating to ensure the count matches the input, since some newlines may be thrown away during the templating. ''' try: i = len(in_str) j = i - 1 while in_str[j] == '\n': j -= 1 return i - 1 - j except IndexError: # Uncommon cases: zero length string and string containing only newlines return i def recursive_check_defined(item): from jinja2.runtime import Undefined if isinstance(item, MutableMapping): for key in item: recursive_check_defined(item[key]) elif isinstance(item, list): for i in item: recursive_check_defined(i) else: if isinstance(item, Undefined): raise AnsibleFilterError("{0} is undefined".format(item)) class AnsibleUndefined(StrictUndefined): ''' A custom Undefined class, which returns further Undefined objects on access, rather than throwing an exception. ''' def __getattr__(self, name): # Return original Undefined object to preserve the first failure context return self def __getitem__(self, key): # Return original Undefined object to preserve the first failure context return self def __repr__(self): return 'AnsibleUndefined' class AnsibleContext(Context): ''' A custom context, which intercepts resolve() calls and sets a flag internally if any variable lookup returns an AnsibleUnsafe value. This flag is checked post-templating, and (when set) will result in the final templated result being wrapped in AnsibleUnsafe. ''' def __init__(self, *args, **kwargs): super(AnsibleContext, self).__init__(*args, **kwargs) self.unsafe = False def _is_unsafe(self, val): ''' Our helper function, which will also recursively check dict and list entries due to the fact that they may be repr'd and contain a key or value which contains jinja2 syntax and would otherwise lose the AnsibleUnsafe value. ''' if isinstance(val, dict): for key in val.keys(): if self._is_unsafe(val[key]): return True elif isinstance(val, list): for item in val: if self._is_unsafe(item): return True elif hasattr(val, '__UNSAFE__'): return True return False def _update_unsafe(self, val): if val is not None and not self.unsafe and self._is_unsafe(val): self.unsafe = True def resolve(self, key): ''' The intercepted resolve(), which uses the helper above to set the internal flag whenever an unsafe variable value is returned. ''' val = super(AnsibleContext, self).resolve(key) self._update_unsafe(val) return val def resolve_or_missing(self, key): val = super(AnsibleContext, self).resolve_or_missing(key) self._update_unsafe(val) return val class JinjaPluginIntercept(MutableMapping): def __init__(self, delegatee, pluginloader, *args, **kwargs): super(JinjaPluginIntercept, self).__init__(*args, **kwargs) self._delegatee = delegatee self._pluginloader = pluginloader if self._pluginloader.class_name == 'FilterModule': self._method_map_name = 'filters' self._dirname = 'filter' elif self._pluginloader.class_name == 'TestModule': self._method_map_name = 'tests' self._dirname = 'test' self._collection_jinja_func_cache = {} # FUTURE: we can cache FQ filter/test calls for the entire duration of a run, since a given collection's impl's # aren't supposed to change during a run def __getitem__(self, key): if not isinstance(key, string_types): raise ValueError('key must be a string') key = to_native(key) if '.' not in key: # might be a built-in value, delegate to base dict return self._delegatee.__getitem__(key) func = self._collection_jinja_func_cache.get(key) if func: return func acr = AnsibleCollectionRef.try_parse_fqcr(key, self._dirname) if not acr: raise KeyError('invalid plugin name: {0}'.format(key)) # FIXME: error handling for bogus plugin name, bogus impl, bogus filter/test pkg = import_module(acr.n_python_package_name) parent_prefix = acr.collection if acr.subdirs: parent_prefix = '{0}.{1}'.format(parent_prefix, acr.subdirs) for dummy, module_name, ispkg in pkgutil.iter_modules(pkg.__path__, prefix=parent_prefix + '.'): if ispkg: continue plugin_impl = self._pluginloader.get(module_name) method_map = getattr(plugin_impl, self._method_map_name) for f in iteritems(method_map()): fq_name = '.'.join((parent_prefix, f[0])) # FIXME: detect/warn on intra-collection function name collisions self._collection_jinja_func_cache[fq_name] = f[1] function_impl = self._collection_jinja_func_cache[key] return function_impl def __setitem__(self, key, value): return self._delegatee.__setitem__(key, value) def __delitem__(self, key): raise NotImplementedError() def __iter__(self): # not strictly accurate since we're not counting dynamically-loaded values return iter(self._delegatee) def __len__(self): # not strictly accurate since we're not counting dynamically-loaded values return len(self._delegatee) class AnsibleEnvironment(Environment): ''' Our custom environment, which simply allows us to override the class-level values for the Template and Context classes used by jinja2 internally. ''' context_class = AnsibleContext template_class = AnsibleJ2Template def __init__(self, *args, **kwargs): super(AnsibleEnvironment, self).__init__(*args, **kwargs) self.filters = JinjaPluginIntercept(self.filters, filter_loader) self.tests = JinjaPluginIntercept(self.tests, test_loader) class Templar: ''' The main class for templating, with the main entry-point of template(). ''' def __init__(self, loader, shared_loader_obj=None, variables=None): variables = {} if variables is None else variables self._loader = loader self._filters = None self._tests = None self._available_variables = variables self._cached_result = {} if loader: self._basedir = loader.get_basedir() else: self._basedir = './' if shared_loader_obj: self._filter_loader = getattr(shared_loader_obj, 'filter_loader') self._test_loader = getattr(shared_loader_obj, 'test_loader') self._lookup_loader = getattr(shared_loader_obj, 'lookup_loader') else: self._filter_loader = filter_loader self._test_loader = test_loader self._lookup_loader = lookup_loader # flags to determine whether certain failures during templating # should result in fatal errors being raised self._fail_on_lookup_errors = True self._fail_on_filter_errors = True self._fail_on_undefined_errors = C.DEFAULT_UNDEFINED_VAR_BEHAVIOR self.environment = AnsibleEnvironment( trim_blocks=True, undefined=AnsibleUndefined, extensions=self._get_extensions(), finalize=self._finalize, loader=FileSystemLoader(self._basedir), ) # the current rendering context under which the templar class is working self.cur_context = None self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string)) self._clean_regex = re.compile(r'(?:%s|%s|%s|%s)' % ( self.environment.variable_start_string, self.environment.block_start_string, self.environment.block_end_string, self.environment.variable_end_string )) self._no_type_regex = re.compile(r'.*?\|\s*(?:%s)(?:\([^\|]*\))?\s*\)?\s*(?:%s)' % ('|'.join(C.STRING_TYPE_FILTERS), self.environment.variable_end_string)) def _get_filters(self): ''' Returns filter plugins, after loading and caching them if need be ''' if self._filters is not None: return self._filters.copy() self._filters = dict() for fp in self._filter_loader.all(): self._filters.update(fp.filters()) return self._filters.copy() def _get_tests(self): ''' Returns tests plugins, after loading and caching them if need be ''' if self._tests is not None: return self._tests.copy() self._tests = dict() for fp in self._test_loader.all(): self._tests.update(fp.tests()) return self._tests.copy() def _get_extensions(self): ''' Return jinja2 extensions to load. If some extensions are set via jinja_extensions in ansible.cfg, we try to load them with the jinja environment. ''' jinja_exts = [] if C.DEFAULT_JINJA2_EXTENSIONS: # make sure the configuration directive doesn't contain spaces # and split extensions in an array jinja_exts = C.DEFAULT_JINJA2_EXTENSIONS.replace(" ", "").split(',') return jinja_exts @property def available_variables(self): return self._available_variables @available_variables.setter def available_variables(self, variables): ''' Sets the list of template variables this Templar instance will use to template things, so we don't have to pass them around between internal methods. We also clear the template cache here, as the variables are being changed. ''' if not isinstance(variables, dict): raise AnsibleAssertionError("the type of 'variables' should be a dict but was a %s" % (type(variables))) self._available_variables = variables self._cached_result = {} def set_available_variables(self, variables): display.deprecated( 'set_available_variables is being deprecated. Use "@available_variables.setter" instead.', version='2.13' ) self.available_variables = variables def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, convert_data=True, static_vars=None, cache=True, disable_lookups=False): ''' Templates (possibly recursively) any given data as input. If convert_bare is set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}') before being sent through the template engine. ''' static_vars = [''] if static_vars is None else static_vars # Don't template unsafe variables, just return them. if hasattr(variable, '__UNSAFE__'): return variable if fail_on_undefined is None: fail_on_undefined = self._fail_on_undefined_errors try: if convert_bare: variable = self._convert_bare_variable(variable) if isinstance(variable, string_types): result = variable if self.is_possibly_template(variable): # Check to see if the string we are trying to render is just referencing a single # var. In this case we don't want to accidentally change the type of the variable # to a string by using the jinja template renderer. We just want to pass it. only_one = self.SINGLE_VAR.match(variable) if only_one: var_name = only_one.group(1) if var_name in self._available_variables: resolved_val = self._available_variables[var_name] if isinstance(resolved_val, NON_TEMPLATED_TYPES): return resolved_val elif resolved_val is None: return C.DEFAULT_NULL_REPRESENTATION # Using a cache in order to prevent template calls with already templated variables sha1_hash = None if cache: variable_hash = sha1(text_type(variable).encode('utf-8')) options_hash = sha1( ( text_type(preserve_trailing_newlines) + text_type(escape_backslashes) + text_type(fail_on_undefined) + text_type(overrides) ).encode('utf-8') ) sha1_hash = variable_hash.hexdigest() + options_hash.hexdigest() if cache and sha1_hash in self._cached_result: result = self._cached_result[sha1_hash] else: result = self.do_template( variable, preserve_trailing_newlines=preserve_trailing_newlines, escape_backslashes=escape_backslashes, fail_on_undefined=fail_on_undefined, overrides=overrides, disable_lookups=disable_lookups, ) if not USE_JINJA2_NATIVE: unsafe = hasattr(result, '__UNSAFE__') if convert_data and not self._no_type_regex.match(variable): # if this looks like a dictionary or list, convert it to such using the safe_eval method if (result.startswith("{") and not result.startswith(self.environment.variable_start_string)) or \ result.startswith("[") or result in ("True", "False"): eval_results = safe_eval(result, include_exceptions=True) if eval_results[1] is None: result = eval_results[0] if unsafe: result = wrap_var(result) else: # FIXME: if the safe_eval raised an error, should we do something with it? pass # we only cache in the case where we have a single variable # name, to make sure we're not putting things which may otherwise # be dynamic in the cache (filters, lookups, etc.) if cache: self._cached_result[sha1_hash] = result return result elif isinstance(variable, (list, tuple)): return [self.template( v, preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides, disable_lookups=disable_lookups, ) for v in variable] elif isinstance(variable, (dict, Mapping)): d = {} # we don't use iteritems() here to avoid problems if the underlying dict # changes sizes due to the templating, which can happen with hostvars for k in variable.keys(): if k not in static_vars: d[k] = self.template( variable[k], preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides, disable_lookups=disable_lookups, ) else: d[k] = variable[k] return d else: return variable except AnsibleFilterError: if self._fail_on_filter_errors: raise else: return variable def is_template(self, data): '''lets us know if data has a template''' if isinstance(data, string_types): return is_template(data, self.environment) elif isinstance(data, (list, tuple)): for v in data: if self.is_template(v): return True elif isinstance(data, dict): for k in data: if self.is_template(k) or self.is_template(data[k]): return True return False templatable = is_template def is_possibly_template(self, data): '''Determines if a string looks like a template, by seeing if it contains a jinja2 start delimiter. Does not guarantee that the string is actually a template. This is different than ``is_template`` which is more strict. This method may return ``True`` on a string that is not templatable. Useful when guarding passing a string for templating, but when you want to allow the templating engine to make the final assessment which may result in ``TemplateSyntaxError``. ''' env = self.environment if isinstance(data, string_types): for marker in (env.block_start_string, env.variable_start_string, env.comment_start_string): if marker in data: return True return False def _convert_bare_variable(self, variable): ''' Wraps a bare string, which may have an attribute portion (ie. foo.bar) in jinja2 variable braces so that it is evaluated properly. ''' if isinstance(variable, string_types): contains_filters = "|" in variable first_part = variable.split("|")[0].split(".")[0].split("[")[0] if (contains_filters or first_part in self._available_variables) and self.environment.variable_start_string not in variable: return "%s%s%s" % (self.environment.variable_start_string, variable, self.environment.variable_end_string) # the variable didn't meet the conditions to be converted, # so just return it as-is return variable def _finalize(self, thing): ''' A custom finalize method for jinja2, which prevents None from being returned. This avoids a string of ``"None"`` as ``None`` has no importance in YAML. If using ANSIBLE_JINJA2_NATIVE we bypass this and return the actual value always ''' if USE_JINJA2_NATIVE: return thing return thing if thing is not None else '' def _fail_lookup(self, name, *args, **kwargs): raise AnsibleError("The lookup `%s` was found, however lookups were disabled from templating" % name) def _now_datetime(self, utc=False, fmt=None): '''jinja2 global function to return current datetime, potentially formatted via strftime''' if utc: now = datetime.datetime.utcnow() else: now = datetime.datetime.now() if fmt: return now.strftime(fmt) return now def _query_lookup(self, name, *args, **kwargs): ''' wrapper for lookup, force wantlist true''' kwargs['wantlist'] = True return self._lookup(name, *args, **kwargs) def _lookup(self, name, *args, **kwargs): instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self) if instance is not None: wantlist = kwargs.pop('wantlist', False) allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS) errors = kwargs.pop('errors', 'strict') from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False) # safely catch run failures per #5059 try: ran = instance.run(loop_terms, variables=self._available_variables, **kwargs) except (AnsibleUndefinedVariable, UndefinedError) as e: raise AnsibleUndefinedVariable(e) except Exception as e: if self._fail_on_lookup_errors: msg = u"An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % \ (name, type(e), to_text(e)) if errors == 'warn': display.warning(msg) elif errors == 'ignore': display.display(msg, log_only=True) else: raise AnsibleError(to_native(msg)) ran = [] if wantlist else None if ran and not allow_unsafe: if wantlist: ran = wrap_var(ran) else: try: ran = wrap_var(",".join(ran)) except TypeError: # Lookup Plugins should always return lists. Throw an error if that's not # the case: if not isinstance(ran, Sequence): raise AnsibleError("The lookup plugin '%s' did not return a list." % name) # The TypeError we can recover from is when the value *inside* of the list # is not a string if len(ran) == 1: ran = wrap_var(ran[0]) else: ran = wrap_var(ran) if self.cur_context: self.cur_context.unsafe = True return ran else: raise AnsibleError("lookup plugin (%s) not found" % name) def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, disable_lookups=False): if USE_JINJA2_NATIVE and not isinstance(data, string_types): return data # For preserving the number of input newlines in the output (used # later in this method) data_newlines = _count_newlines_from_end(data) if fail_on_undefined is None: fail_on_undefined = self._fail_on_undefined_errors try: # allows template header overrides to change jinja2 options. if overrides is None: myenv = self.environment.overlay() else: myenv = self.environment.overlay(overrides) # Get jinja env overrides from template if hasattr(data, 'startswith') and data.startswith(JINJA2_OVERRIDE): eol = data.find('\n') line = data[len(JINJA2_OVERRIDE):eol] data = data[eol + 1:] for pair in line.split(','): (key, val) = pair.split(':') key = key.strip() setattr(myenv, key, ast.literal_eval(val.strip())) # Adds Ansible custom filters and tests myenv.filters.update(self._get_filters()) myenv.tests.update(self._get_tests()) if escape_backslashes: # Allow users to specify backslashes in playbooks as "\\" instead of as "\\\\". data = _escape_backslashes(data, myenv) try: t = myenv.from_string(data) except TemplateSyntaxError as e: raise AnsibleError("template error while templating string: %s. String: %s" % (to_native(e), to_native(data))) except Exception as e: if 'recursion' in to_native(e): raise AnsibleError("recursive loop detected in template string: %s" % to_native(data)) else: return data # jinja2 global is inconsistent across versions, this normalizes them t.globals['dict'] = dict if disable_lookups: t.globals['query'] = t.globals['q'] = t.globals['lookup'] = self._fail_lookup else: t.globals['lookup'] = self._lookup t.globals['query'] = t.globals['q'] = self._query_lookup t.globals['now'] = self._now_datetime t.globals['finalize'] = self._finalize jvars = AnsibleJ2Vars(self, t.globals) self.cur_context = new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try: res = j2_concat(rf) if getattr(new_context, 'unsafe', False): res = wrap_var(res) except TypeError as te: if 'AnsibleUndefined' in to_native(te): errmsg = "Unable to look up a name or access an attribute in template string (%s).\n" % to_native(data) errmsg += "Make sure your variable name does not contain invalid characters like '-': %s" % to_native(te) raise AnsibleUndefinedVariable(errmsg) else: display.debug("failing because of a type error, template data is: %s" % to_text(data)) raise AnsibleError("Unexpected templating type error occurred on (%s): %s" % (to_native(data), to_native(te))) if USE_JINJA2_NATIVE and not isinstance(res, string_types): return res if preserve_trailing_newlines: # The low level calls above do not preserve the newline # characters at the end of the input data, so we use the # calculate the difference in newlines and append them # to the resulting output for parity # # jinja2 added a keep_trailing_newline option in 2.7 when # creating an Environment. That would let us make this code # better (remove a single newline if # preserve_trailing_newlines is False). Once we can depend on # that version being present, modify our code to set that when # initializing self.environment and remove a single trailing # newline here if preserve_newlines is False. res_newlines = _count_newlines_from_end(res) if data_newlines > res_newlines: res += self.environment.newline_sequence * (data_newlines - res_newlines) return res except (UndefinedError, AnsibleUndefinedVariable) as e: if fail_on_undefined: raise AnsibleUndefinedVariable(e) else: display.debug("Ignoring undefined failure: %s" % to_text(e)) return data # for backwards compatibility in case anyone is using old private method directly _do_template = do_template
closed
ansible/ansible
https://github.com/ansible/ansible
63,091
ios_banner: unneeded change when multiple banners are configured in IOS 12.x
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY When multiple banners are present in a configuration and if the device does not support the "show banner" command, ios_banner incorrectly detects a change is needed in all banners but the last. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ios_banner ##### ANSIBLE VERSION ``` ansible 2.10.0.dev0 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/kalimsshar/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /home/kalimsshar/dev/ansible/ansible/lib/ansible executable location = /home/kalimsshar/dev/ansible/ansible/bin/ansible python version = 2.7.5 (default, Aug 7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] ``` ##### CONFIGURATION N/A (no output from "ansible-config dump --only-changed") ##### OS / ENVIRONMENT Tested on multiple Cisco devices (switches and routers) using IOS 12.x with ansible running on Centos 7.7.1908 ##### STEPS TO REPRODUCE Create a playbook as follow, using the same banners that the ones on the Cisco device. ```yaml --- - hosts: Switch1 gather_facts: no vars: ansible_connection: network_cli ansible_network_os: ios tasks: - name: "set login banner" ios_banner: banner: login text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present - name: "set exec banner" ios_banner: banner: exec text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Expected for ios_banner to detect no change is needed. ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** ok: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** changed: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/63091
https://github.com/ansible/ansible/pull/63092
9d91e6275e248ead120cb36b8912c00a28e4c95b
01a92f0191de904ca8351cbfd1516e1aee874372
2019-10-03T14:31:55Z
python
2019-10-25T18:20:00Z
lib/ansible/modules/network/ios/ios_banner.py
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: ios_banner version_added: "2.3" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" short_description: Manage multiline banners on Cisco IOS devices description: - This will configure both login and motd banners on remote devices running Cisco IOS. It allows playbooks to add or remote banner text from the active running configuration. extends_documentation_fragment: ios notes: - Tested against IOS 15.6 options: banner: description: - Specifies which banner should be configured on the remote device. In Ansible 2.4 and earlier only I(login) and I(motd) were supported. required: true choices: ['login', 'motd', 'exec', 'incoming', 'slip-ppp'] text: description: - The banner text that should be present in the remote device running configuration. This argument accepts a multiline string, with no empty lines. Requires I(state=present). state: description: - Specifies whether or not the configuration is present in the current devices active running configuration. default: present choices: ['present', 'absent'] """ EXAMPLES = """ - name: configure the login banner ios_banner: banner: login text: | this is my login banner that contains a multiline string state: present - name: remove the motd banner ios_banner: banner: motd state: absent - name: Configure banner from file ios_banner: banner: motd text: "{{ lookup('file', './config_partial/raw_banner.cfg') }}" state: present """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always type: list sample: - banner login - this is my login banner - that contains a multiline - string """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import exec_command from ansible.module_utils.network.ios.ios import load_config from ansible.module_utils.network.ios.ios import ios_argument_spec import re def map_obj_to_commands(updates, module): commands = list() want, have = updates state = module.params['state'] if state == 'absent' and 'text' in have.keys() and have['text']: commands.append('no banner %s' % module.params['banner']) elif state == 'present': if want['text'] and (want['text'] != have.get('text')): banner_cmd = 'banner %s' % module.params['banner'] banner_cmd += ' @\n' banner_cmd += want['text'].strip() banner_cmd += '\n@' commands.append(banner_cmd) return commands def map_config_to_obj(module): rc, out, err = exec_command(module, 'show banner %s' % module.params['banner']) if rc == 0: output = out else: rc, out, err = exec_command(module, 'show running-config | begin banner %s' % module.params['banner']) if out: output = re.search(r'\^C(.*)\^C', out, re.S).group(1).strip() else: output = None obj = {'banner': module.params['banner'], 'state': 'absent'} if output: obj['text'] = output obj['state'] = 'present' return obj def map_params_to_obj(module): text = module.params['text'] if text: text = str(text).strip() return { 'banner': module.params['banner'], 'text': text, 'state': module.params['state'] } def main(): """ main entry point for module execution """ argument_spec = dict( banner=dict(required=True, choices=['login', 'motd', 'exec', 'incoming', 'slip-ppp']), text=dict(), state=dict(default='present', choices=['present', 'absent']) ) argument_spec.update(ios_argument_spec) required_if = [('state', 'present', ('text',))] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands((want, have), module) result['commands'] = commands if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,091
ios_banner: unneeded change when multiple banners are configured in IOS 12.x
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY When multiple banners are present in a configuration and if the device does not support the "show banner" command, ios_banner incorrectly detects a change is needed in all banners but the last. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ios_banner ##### ANSIBLE VERSION ``` ansible 2.10.0.dev0 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/kalimsshar/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /home/kalimsshar/dev/ansible/ansible/lib/ansible executable location = /home/kalimsshar/dev/ansible/ansible/bin/ansible python version = 2.7.5 (default, Aug 7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] ``` ##### CONFIGURATION N/A (no output from "ansible-config dump --only-changed") ##### OS / ENVIRONMENT Tested on multiple Cisco devices (switches and routers) using IOS 12.x with ansible running on Centos 7.7.1908 ##### STEPS TO REPRODUCE Create a playbook as follow, using the same banners that the ones on the Cisco device. ```yaml --- - hosts: Switch1 gather_facts: no vars: ansible_connection: network_cli ansible_network_os: ios tasks: - name: "set login banner" ios_banner: banner: login text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present - name: "set exec banner" ios_banner: banner: exec text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Expected for ios_banner to detect no change is needed. ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** ok: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** changed: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/63091
https://github.com/ansible/ansible/pull/63092
9d91e6275e248ead120cb36b8912c00a28e4c95b
01a92f0191de904ca8351cbfd1516e1aee874372
2019-10-03T14:31:55Z
python
2019-10-25T18:20:00Z
test/integration/targets/ios_banner/tests/cli/multiple-login-exec.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
63,091
ios_banner: unneeded change when multiple banners are configured in IOS 12.x
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY When multiple banners are present in a configuration and if the device does not support the "show banner" command, ios_banner incorrectly detects a change is needed in all banners but the last. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ios_banner ##### ANSIBLE VERSION ``` ansible 2.10.0.dev0 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/kalimsshar/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /home/kalimsshar/dev/ansible/ansible/lib/ansible executable location = /home/kalimsshar/dev/ansible/ansible/bin/ansible python version = 2.7.5 (default, Aug 7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] ``` ##### CONFIGURATION N/A (no output from "ansible-config dump --only-changed") ##### OS / ENVIRONMENT Tested on multiple Cisco devices (switches and routers) using IOS 12.x with ansible running on Centos 7.7.1908 ##### STEPS TO REPRODUCE Create a playbook as follow, using the same banners that the ones on the Cisco device. ```yaml --- - hosts: Switch1 gather_facts: no vars: ansible_connection: network_cli ansible_network_os: ios tasks: - name: "set login banner" ios_banner: banner: login text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present - name: "set exec banner" ios_banner: banner: exec text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Expected for ios_banner to detect no change is needed. ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** ok: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** changed: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/63091
https://github.com/ansible/ansible/pull/63092
9d91e6275e248ead120cb36b8912c00a28e4c95b
01a92f0191de904ca8351cbfd1516e1aee874372
2019-10-03T14:31:55Z
python
2019-10-25T18:20:00Z
test/units/modules/network/ios/fixtures/ios_banner_show_running_config_ios12.txt
closed
ansible/ansible
https://github.com/ansible/ansible
63,091
ios_banner: unneeded change when multiple banners are configured in IOS 12.x
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY When multiple banners are present in a configuration and if the device does not support the "show banner" command, ios_banner incorrectly detects a change is needed in all banners but the last. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ios_banner ##### ANSIBLE VERSION ``` ansible 2.10.0.dev0 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/kalimsshar/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /home/kalimsshar/dev/ansible/ansible/lib/ansible executable location = /home/kalimsshar/dev/ansible/ansible/bin/ansible python version = 2.7.5 (default, Aug 7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] ``` ##### CONFIGURATION N/A (no output from "ansible-config dump --only-changed") ##### OS / ENVIRONMENT Tested on multiple Cisco devices (switches and routers) using IOS 12.x with ansible running on Centos 7.7.1908 ##### STEPS TO REPRODUCE Create a playbook as follow, using the same banners that the ones on the Cisco device. ```yaml --- - hosts: Switch1 gather_facts: no vars: ansible_connection: network_cli ansible_network_os: ios tasks: - name: "set login banner" ios_banner: banner: login text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present - name: "set exec banner" ios_banner: banner: exec text: | ********************************************* * * * Actual banner configured on device * * * ********************************************* state: present ``` ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Expected for ios_banner to detect no change is needed. ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** ok: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ``` ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ``` $ ansible-playbook -k -i hosts.ini banner.yml SSH password: TASK [set login banner] ********************************************************************************************************************************************************************************************** ok: [Switch1] TASK [set exec banner] *********************************************************************************************************************************************************************************************** changed: [Switch1] PLAY RECAP *********************************************************************************************************************************************************************************************************** Switch1 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/63091
https://github.com/ansible/ansible/pull/63092
9d91e6275e248ead120cb36b8912c00a28e4c95b
01a92f0191de904ca8351cbfd1516e1aee874372
2019-10-03T14:31:55Z
python
2019-10-25T18:20:00Z
test/units/modules/network/ios/test_ios_banner.py
# This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from units.compat.mock import patch from ansible.modules.network.ios import ios_banner from units.modules.utils import set_module_args from .ios_module import TestIosModule, load_fixture class TestIosBannerModule(TestIosModule): module = ios_banner def setUp(self): super(TestIosBannerModule, self).setUp() self.mock_exec_command = patch('ansible.modules.network.ios.ios_banner.exec_command') self.exec_command = self.mock_exec_command.start() self.mock_load_config = patch('ansible.modules.network.ios.ios_banner.load_config') self.load_config = self.mock_load_config.start() def tearDown(self): super(TestIosBannerModule, self).tearDown() self.mock_exec_command.stop() self.mock_load_config.stop() def load_fixtures(self, commands=None): self.exec_command.return_value = (0, load_fixture('ios_banner_show_banner.txt').strip(), None) self.load_config.return_value = dict(diff=None, session='session') def test_ios_banner_create(self): for banner_type in ('login', 'motd', 'exec', 'incoming', 'slip-ppp'): set_module_args(dict(banner=banner_type, text='test\nbanner\nstring')) commands = ['banner {0} @\ntest\nbanner\nstring\n@'.format(banner_type)] self.execute_module(changed=True, commands=commands) def test_ios_banner_remove(self): set_module_args(dict(banner='login', state='absent')) commands = ['no banner login'] self.execute_module(changed=True, commands=commands) def test_ios_banner_nochange(self): banner_text = load_fixture('ios_banner_show_banner.txt').strip() set_module_args(dict(banner='login', text=banner_text)) self.execute_module()
closed
ansible/ansible
https://github.com/ansible/ansible
59,021
k8s_scale fails on "KeyError: merge_type"
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY It is not possible to use k8s_scale due to missing key merge_type. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME k8s_scale ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.2 config file = /Users/chbr/repos/work/components/helm/ansible.cfg configured module search path = ['/Users/chbr/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.3 (default, Mar 27 2019, 09:23:15) [Clang 10.0.1 (clang-1001.0.46.3)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Client is macOS 10.14.4 Cluster is OKD 3.11 ##### STEPS TO REPRODUCE On a newly deployed OKD cluster I fired up a Tiller service successfully. But deleting it via the `k8s` module does not delete the pods because of some issue in Kubernetes API. So my attempted work around is to scale down the deployment before deleting it. <!--- Paste example playbooks or commands between quotes below --> ```yaml - name: Scale down Tiller k8s_scale: kind: Deployment name: tiller-deploy api_version: v1 namespace: myproject replicas: 0 ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> I expect Ansible to succeed and the deployment to be scaled down to 0 replicas. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below /Users/chbr/.ansible/tmp/ansible-tmp-1562923350.045843-76777999244172/AnsiballZ_k8s_scale.py:18: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp Traceback (most recent call last): File "/Users/chbr/.ansible/tmp/ansible-tmp-1562923350.045843-76777999244172/AnsiballZ_k8s_scale.py", line 114, in <module> _ansiballz_main() File "/Users/chbr/.ansible/tmp/ansible-tmp-1562923350.045843-76777999244172/AnsiballZ_k8s_scale.py", line 106, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/Users/chbr/.ansible/tmp/ansible-tmp-1562923350.045843-76777999244172/AnsiballZ_k8s_scale.py", line 49, in invoke_module imp.load_module('__main__', mod, module, MOD_DESC) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/imp.py", line 234, in load_module return load_source(name, filename, file) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/imp.py", line 169, in load_source module = _exec(spec, sys.modules[name]) File "<frozen importlib._bootstrap>", line 630, in _exec File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/var/folders/d0/bmn8x1693sv_fcgb8kbyv4s40000gn/T/ansible_k8s_scale_payload_q4dt8qvw/__main__.py", line 129, in <module> File "/var/folders/d0/bmn8x1693sv_fcgb8kbyv4s40000gn/T/ansible_k8s_scale_payload_q4dt8qvw/__main__.py", line 125, in main File "/var/folders/d0/bmn8x1693sv_fcgb8kbyv4s40000gn/T/ansible_k8s_scale_payload_q4dt8qvw/ansible_k8s_scale_payload.zip/ansible/module_utils/k8s/raw.py", line 115, in __init__ KeyError: 'merge_type' ```
https://github.com/ansible/ansible/issues/59021
https://github.com/ansible/ansible/pull/59887
01a92f0191de904ca8351cbfd1516e1aee874372
e60cdc310d5344c00b4f49c9f7dde78d206b25ae
2019-07-12T09:38:40Z
python
2019-10-25T19:44:39Z
lib/ansible/module_utils/k8s/scale.py
# # Copyright 2018 Red Hat | Ansible # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function import copy import math import time from ansible.module_utils.k8s.raw import KubernetesRawModule from ansible.module_utils.k8s.common import AUTH_ARG_SPEC, COMMON_ARG_SPEC try: from openshift import watch from openshift.dynamic.client import ResourceInstance from openshift.helper.exceptions import KubernetesException except ImportError as exc: class KubernetesException(Exception): pass SCALE_ARG_SPEC = { 'replicas': {'type': 'int', 'required': True}, 'current_replicas': {'type': 'int'}, 'resource_version': {}, 'wait': {'type': 'bool', 'default': True}, 'wait_timeout': {'type': 'int', 'default': 20} } class KubernetesAnsibleScaleModule(KubernetesRawModule): def execute_module(self): definition = self.resource_definitions[0] self.client = self.get_api_client() name = definition['metadata']['name'] namespace = definition['metadata'].get('namespace') api_version = definition['apiVersion'] kind = definition['kind'] current_replicas = self.params.get('current_replicas') replicas = self.params.get('replicas') resource_version = self.params.get('resource_version') wait = self.params.get('wait') wait_time = self.params.get('wait_timeout') existing = None existing_count = None return_attributes = dict(changed=False, result=dict()) resource = self.find_resource(kind, api_version, fail=True) try: existing = resource.get(name=name, namespace=namespace) return_attributes['result'] = existing.to_dict() except KubernetesException as exc: self.fail_json(msg='Failed to retrieve requested object: {0}'.format(exc), error=exc.value.get('status')) if self.kind == 'job': existing_count = existing.spec.parallelism elif hasattr(existing.spec, 'replicas'): existing_count = existing.spec.replicas if existing_count is None: self.fail_json(msg='Failed to retrieve the available count for the requested object.') if resource_version and resource_version != existing.metadata.resourceVersion: self.exit_json(**return_attributes) if current_replicas is not None and existing_count != current_replicas: self.exit_json(**return_attributes) if existing_count != replicas: return_attributes['changed'] = True if not self.check_mode: if self.kind == 'job': existing.spec.parallelism = replicas k8s_obj = resource.patch(existing.to_dict()) else: k8s_obj = self.scale(resource, existing, replicas, wait, wait_time) return_attributes['result'] = k8s_obj.to_dict() self.exit_json(**return_attributes) @property def argspec(self): args = copy.deepcopy(COMMON_ARG_SPEC) args.pop('state') args.pop('force') args.update(AUTH_ARG_SPEC) args.update(SCALE_ARG_SPEC) return args def scale(self, resource, existing_object, replicas, wait, wait_time): name = existing_object.metadata.name namespace = existing_object.metadata.namespace if not hasattr(resource, 'scale'): self.fail_json( msg="Cannot perform scale on resource of kind {0}".format(resource.kind) ) scale_obj = {'metadata': {'name': name, 'namespace': namespace}, 'spec': {'replicas': replicas}} return_obj = None stream = None if wait: w, stream = self._create_stream(resource, namespace, wait_time) try: resource.scale.patch(body=scale_obj) except Exception as exc: self.fail_json( msg="Scale request failed: {0}".format(exc) ) if wait and stream is not None: return_obj = self._read_stream(resource, w, stream, name, replicas) if not return_obj: return_obj = self._wait_for_response(resource, name, namespace) return return_obj def _create_stream(self, resource, namespace, wait_time): """ Create a stream of events for the object """ w = None stream = None try: w = watch.Watch() w._api_client = self.client.client if namespace: stream = w.stream(resource.get, serialize=False, namespace=namespace, timeout_seconds=wait_time) else: stream = w.stream(resource.get, serialize=False, namespace=namespace, timeout_seconds=wait_time) except KubernetesException: pass return w, stream def _read_stream(self, resource, watcher, stream, name, replicas): """ Wait for ready_replicas to equal the requested number of replicas. """ return_obj = None try: for event in stream: if event.get('object'): obj = ResourceInstance(resource, event['object']) if obj.metadata.name == name and hasattr(obj, 'status'): if replicas == 0: if not hasattr(obj.status, 'readyReplicas') or not obj.status.readyReplicas: return_obj = obj watcher.stop() break if hasattr(obj.status, 'readyReplicas') and obj.status.readyReplicas == replicas: return_obj = obj watcher.stop() break except Exception as exc: self.fail_json(msg="Exception reading event stream: {0}".format(exc)) if not return_obj: self.fail_json(msg="Error fetching the patched object. Try a higher wait_timeout value.") if replicas and return_obj.status.readyReplicas is None: self.fail_json(msg="Failed to fetch the number of ready replicas. Try a higher wait_timeout value.") if replicas and return_obj.status.readyReplicas != replicas: self.fail_json(msg="Number of ready replicas is {0}. Failed to reach {1} ready replicas within " "the wait_timeout period.".format(return_obj.status.ready_replicas, replicas)) return return_obj def _wait_for_response(self, resource, name, namespace): """ Wait for an API response """ tries = 0 half = math.ceil(20 / 2) obj = None while tries <= half: obj = resource.get(name=name, namespace=namespace) if obj: break tries += 2 time.sleep(2) return obj
closed
ansible/ansible
https://github.com/ansible/ansible
61,332
vmware_host_firewall_manager: TypeError: 'NoneType' object is not subscriptable
##### SUMMARY The function test of `vmware_host_firewall_manager` is currently broken. This seems to be a regression introduced with https://github.com/ansible/ansible/pull/56733. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME vmware_host_firewall_manager ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ``` ##### STEPS TO REPRODUCE The first step of the functional test: https://github.com/ansible/ansible/blob/devel/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml ```yaml - name: Disable the Firewall vvold rule on the ESXi vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: '{{ ccr1 }}' validate_certs: no rules: - name: vvold enabled: False ``` ##### ACTUAL RESULTS ```paste below TASK [vmware_host_firewall_manager : Disable the Firewall vvold rule on the ESXi] **************************************************************** task path: /home/goneri/.ansible/test/tmp/vmware_host_firewall_manager-mn0bxgye-ÅÑŚÌβŁÈ/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml:11 <testhost> ESTABLISH LOCAL CONNECTION FOR USER: goneri <testhost> EXEC /bin/sh -c 'echo ~goneri && sleep 0' <testhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" && echo ansible-tmp-1566836629.9222088-161847597588297="` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" ) && sleep 0' Using module file /home/goneri/git_repos/ansible_projects/b/lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py <testhost> PUT /home/goneri/.ansible/tmp/ansible-local-25543igy5eduv/tmp1tecxld1 TO /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py <testhost> EXEC /bin/sh -c 'chmod u+x /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'ESXI1_HOSTNAME=esxi1.test ESXI1_PASSWORD='"'"'!234AaAa56'"'"' ESXI1_USERNAME=root ESXI2_HOSTNAME=esxi2.test ESXI2_PASSWORD='"'"'!234AaAa56'"'"' ESXI2_USERNAME=root VCENTER_HOSTNAME=vcenter.test VCENTER_PASSWORD='"'"'!234AaAa56'"'"' [email protected] VMWARE_VALIDATE_CERTS=no /home/goneri/git_repos/ansible_projects/b/.virtualenv/py37/bin/python /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'rm -f -r /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 139, in <module> _ansiballz_main() File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 131, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 65, in invoke_module spec.loader.exec_module(module) File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 367, in <module> File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 363, in main File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 238, in ensure TypeError: 'NoneType' object is not subscriptable fatal: [testhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 139, in <module>\n _ansiballz_main()\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 131, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 65, in invoke_module\n spec.loader.exec_module(module)\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 367, in <module>\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 363, in main\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 238, in ensure\nTypeError: 'NoneType' object is not subscriptable\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
https://github.com/ansible/ansible/issues/61332
https://github.com/ansible/ansible/pull/63567
358574d57f2b411e820cbf4d00a8249ac8291cb9
039c770a9539314e2703781d9c42da20ed5904fb
2019-08-26T17:45:19Z
python
2019-10-28T17:01:02Z
changelogs/fragments/vmware_host_firewall_manager_fix_61332.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
61,332
vmware_host_firewall_manager: TypeError: 'NoneType' object is not subscriptable
##### SUMMARY The function test of `vmware_host_firewall_manager` is currently broken. This seems to be a regression introduced with https://github.com/ansible/ansible/pull/56733. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME vmware_host_firewall_manager ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ``` ##### STEPS TO REPRODUCE The first step of the functional test: https://github.com/ansible/ansible/blob/devel/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml ```yaml - name: Disable the Firewall vvold rule on the ESXi vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: '{{ ccr1 }}' validate_certs: no rules: - name: vvold enabled: False ``` ##### ACTUAL RESULTS ```paste below TASK [vmware_host_firewall_manager : Disable the Firewall vvold rule on the ESXi] **************************************************************** task path: /home/goneri/.ansible/test/tmp/vmware_host_firewall_manager-mn0bxgye-ÅÑŚÌβŁÈ/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml:11 <testhost> ESTABLISH LOCAL CONNECTION FOR USER: goneri <testhost> EXEC /bin/sh -c 'echo ~goneri && sleep 0' <testhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" && echo ansible-tmp-1566836629.9222088-161847597588297="` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" ) && sleep 0' Using module file /home/goneri/git_repos/ansible_projects/b/lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py <testhost> PUT /home/goneri/.ansible/tmp/ansible-local-25543igy5eduv/tmp1tecxld1 TO /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py <testhost> EXEC /bin/sh -c 'chmod u+x /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'ESXI1_HOSTNAME=esxi1.test ESXI1_PASSWORD='"'"'!234AaAa56'"'"' ESXI1_USERNAME=root ESXI2_HOSTNAME=esxi2.test ESXI2_PASSWORD='"'"'!234AaAa56'"'"' ESXI2_USERNAME=root VCENTER_HOSTNAME=vcenter.test VCENTER_PASSWORD='"'"'!234AaAa56'"'"' [email protected] VMWARE_VALIDATE_CERTS=no /home/goneri/git_repos/ansible_projects/b/.virtualenv/py37/bin/python /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'rm -f -r /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 139, in <module> _ansiballz_main() File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 131, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 65, in invoke_module spec.loader.exec_module(module) File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 367, in <module> File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 363, in main File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 238, in ensure TypeError: 'NoneType' object is not subscriptable fatal: [testhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 139, in <module>\n _ansiballz_main()\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 131, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 65, in invoke_module\n spec.loader.exec_module(module)\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 367, in <module>\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 363, in main\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 238, in ensure\nTypeError: 'NoneType' object is not subscriptable\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
https://github.com/ansible/ansible/issues/61332
https://github.com/ansible/ansible/pull/63567
358574d57f2b411e820cbf4d00a8249ac8291cb9
039c770a9539314e2703781d9c42da20ed5904fb
2019-08-26T17:45:19Z
python
2019-10-28T17:01:02Z
lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: vmware_host_firewall_manager short_description: Manage firewall configurations about an ESXi host description: - This module can be used to manage firewall configurations about an ESXi host when ESXi hostname or Cluster name is given. version_added: '2.5' author: - Abhijeet Kasurde (@Akasurde) - Aaron Longchamps (@alongchamps) notes: - Tested on vSphere 6.0, vSphere 6.5 requirements: - python >= 2.6 - PyVmomi options: cluster_name: description: - Name of the cluster. - Firewall settings are applied to every ESXi host system in given cluster. - If C(esxi_hostname) is not given, this parameter is required. type: str esxi_hostname: description: - ESXi hostname. - Firewall settings are applied to this ESXi host system. - If C(cluster_name) is not given, this parameter is required. type: str rules: description: - A list of Rule set which needs to be managed. - Each member of list is rule set name and state to be set the rule. - Both rule name and rule state are required parameters. - Additional IPs and networks can also be specified - Please see examples for more information. default: [] type: list extends_documentation_fragment: vmware.documentation ''' EXAMPLES = r''' - name: Enable vvold rule set for all ESXi Host in given Cluster vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: cluster_name rules: - name: vvold enabled: True delegate_to: localhost - name: Enable vvold rule set for an ESXi Host vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' esxi_hostname: '{{ esxi_hostname }}' rules: - name: vvold enabled: True delegate_to: localhost - name: Manage multiple rule set for an ESXi Host vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' esxi_hostname: '{{ esxi_hostname }}' rules: - name: vvold enabled: True - name: CIMHttpServer enabled: False delegate_to: localhost - name: Manage IP and network based firewall permissions for ESXi vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' esxi_hostname: '{{ esxi_hostname }}' rules: - name: gdbserver enabled: True allowed_hosts: - all_ip: False ip_address: 192.168.20.10 - name: CIMHttpServer enabled: True allowed_hosts: - all_ip: False ip_network: 192.168.100.0/24 - name: remoteSerialPort enabled: True allowed_hosts: - all_ip: False ip_address: 192.168.100.11 ip_network: 192.168.200.0/24 delegate_to: localhost ''' RETURN = r''' rule_set_state: description: - dict with hostname as key and dict with firewall rule set facts as value returned: success type: dict sample: { "rule_set_state": { "localhost.localdomain": { "CIMHttpServer": { "current_state": False, "desired_state": False, "previous_state": True, "allowed_hosts": { "current_allowed_all": True, "previous_allowed_all": True, "desired_allowed_all": True, "current_allowed_ip": [], "previous_allowed_ip": [], "desired_allowed_ip": [], "current_allowed_networks": [], "previous_allowed_networks": [], "desired_allowed_networks": [], } }, "remoteSerialPort": { "current_state": True, "desired_state": True, "previous_state": True, "allowed_hosts": { "current_allowed_all": False, "previous_allowed_all": True, "desired_allowed_all": False, "current_allowed_ip": ["192.168.100.11"], "previous_allowed_ip": [], "desired_allowed_ip": ["192.168.100.11"], "current_allowed_networks": ["192.168.200.0/24"], "previous_allowed_networks": [], "desired_allowed_networks": ["192.168.200.0/24"], } } } } } ''' try: from pyVmomi import vim except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi from ansible.module_utils._text import to_native from ansible.module_utils.compat import ipaddress class VmwareFirewallManager(PyVmomi): def __init__(self, module): super(VmwareFirewallManager, self).__init__(module) cluster_name = self.params.get('cluster_name', None) esxi_host_name = self.params.get('esxi_hostname', None) self.options = self.params.get('options', dict()) self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name) self.firewall_facts = dict() self.rule_options = self.module.params.get("rules") self.gather_rule_set() def gather_rule_set(self): for host in self.hosts: self.firewall_facts[host.name] = {} firewall_system = host.configManager.firewallSystem if firewall_system: for rule_set_obj in firewall_system.firewallInfo.ruleset: temp_rule_dict = dict() temp_rule_dict['enabled'] = rule_set_obj.enabled allowed_host = rule_set_obj.allowedHosts rule_allow_host = dict() rule_allow_host['ip_address'] = allowed_host.ipAddress rule_allow_host['ip_network'] = [ip.network + "/" + str(ip.prefixLength) for ip in allowed_host.ipNetwork] rule_allow_host['all_ip'] = allowed_host.allIp temp_rule_dict['allowed_hosts'] = rule_allow_host self.firewall_facts[host.name][rule_set_obj.key] = temp_rule_dict def ensure(self): """ Function to ensure rule set configuration """ fw_change_list = [] enable_disable_changed = False allowed_ip_changed = False results = dict(changed=False, rule_set_state=dict()) for host in self.hosts: firewall_system = host.configManager.firewallSystem if firewall_system is None: continue results['rule_set_state'][host.name] = dict() for rule_option in self.rule_options: rule_name = rule_option.get('name', None) if rule_name is None: self.module.fail_json(msg="Please specify rule.name for rule set" " as it is required parameter.") if rule_name not in self.firewall_facts[host.name]: self.module.fail_json(msg="rule named '%s' wasn't found." % rule_name) rule_enabled = rule_option.get('enabled', None) if rule_enabled is None: self.module.fail_json(msg="Please specify rules.enabled for rule set" " %s as it is required parameter." % rule_name) # validate IP addresses are valid rule_config = rule_option.get('allowed_hosts', None) if 'ip_address' in rule_config[0].keys(): for ip_addr in rule_config[0]['ip_address']: try: ip = ipaddress.ip_address(ip_addr) except ValueError: self.module.fail_json(msg="The provided IP address %s is not a valid IP" " for the rule %s" % (ip_addr, rule_name)) # validate provided subnets are valid networks if 'ip_network' in rule_config[0].keys(): for ip_net in rule_config[0]['ip_network']: try: network_validation = ipaddress.ip_network(ip_net) except ValueError: self.module.fail_json(msg="The provided network %s is not a valid network" " for the rule %s" % (ip_net, rule_name)) current_rule_state = self.firewall_facts[host.name][rule_name]['enabled'] if current_rule_state != rule_enabled: try: if not self.module.check_mode: if rule_enabled: firewall_system.EnableRuleset(id=rule_name) else: firewall_system.DisableRuleset(id=rule_name) # keep track of changes as we go enable_disable_changed = True except vim.fault.NotFound as not_found: self.module.fail_json(msg="Failed to enable rule set %s as" " rule set id is unknown : %s" % (rule_name, to_native(not_found.msg))) except vim.fault.HostConfigFault as host_config_fault: self.module.fail_json(msg="Failed to enabled rule set %s as an internal" " error happened while reconfiguring" " rule set : %s" % (rule_name, to_native(host_config_fault.msg))) # save variables here for comparison later and change tracking # also covers cases where inputs may be null permitted_networking = self.firewall_facts[host.name][rule_name] rule_allows_all = permitted_networking['allowed_hosts']['all_ip'] playbook_allows_all = rule_config[0]['all_ip'] rule_allowed_ip = set(permitted_networking['allowed_hosts']['ip_address']) playbook_allowed_ip = set(rule_config[0].get('ip_address', '')) rule_allowed_networks = set(permitted_networking['allowed_hosts']['ip_network']) playbook_allowed_networks = set(rule_config[0].get('ip_network', '')) # compare what is configured on the firewall rule with what the playbook provides allowed_all_ips_different = bool(rule_allows_all != playbook_allows_all) ip_list_different = bool(rule_allowed_ip != playbook_allowed_ip) ip_network_different = bool(rule_allowed_networks != playbook_allowed_networks) # apply everything here in one function call if allowed_all_ips_different is True or ip_list_different is True or ip_network_different is True: try: allowed_ip_changed = True if not self.module.check_mode: # setup spec firewall_spec = vim.host.Ruleset.RulesetSpec() firewall_spec.allowedHosts = vim.host.Ruleset.IpList() firewall_spec.allowedHosts.allIp = rule_config[0].get('all_ip', True) firewall_spec.allowedHosts.ipAddress = rule_config[0].get('ip_address', None) firewall_spec.allowedHosts.ipNetwork = [] if 'ip_network' in rule_config[0].keys(): for allowed_network in rule_config[0].get('ip_network', None): tmp_ip_network_spec = vim.host.Ruleset.IpNetwork() tmp_ip_network_spec.network = allowed_network.split("/")[0] tmp_ip_network_spec.prefixLength = int(allowed_network.split("/")[1]) firewall_spec.allowedHosts.ipNetwork.append(tmp_ip_network_spec) firewall_system.UpdateRuleset(id=rule_name, spec=firewall_spec) except vim.fault.NotFound as not_found: self.module.fail_json(msg="Failed to configure rule set %s as" " rule set id is unknown : %s" % (rule_name, to_native(not_found.msg))) except vim.fault.HostConfigFault as host_config_fault: self.module.fail_json(msg="Failed to configure rule set %s as an internal" " error happened while reconfiguring" " rule set : %s" % (rule_name, to_native(host_config_fault.msg))) except vim.fault.RuntimeFault as runtime_fault: self.module.fail_json(msg="Failed to configure the rule set %s as a runtime" " error happened while applying the reconfiguration:" " %s" % (rule_name, to_native(runtime_fault.msg))) results['rule_set_state'][host.name][rule_name] = dict(current_state=rule_enabled, previous_state=current_rule_state, desired_state=rule_enabled, current_allowed_all=playbook_allows_all, previous_allowed_all=permitted_networking['allowed_hosts']['all_ip'], desired_allowed_all=playbook_allows_all, current_allowed_ip=playbook_allowed_ip, previous_allowed_ip=set(permitted_networking['allowed_hosts']['ip_address']), desired_allowed_ip=playbook_allowed_ip, current_allowed_networks=playbook_allowed_networks, previous_allowed_networks=set(permitted_networking['allowed_hosts']['ip_network']), desired_allowed_networks=playbook_allowed_networks ) if enable_disable_changed or allowed_ip_changed: fw_change_list.append(True) if any(fw_change_list): results['changed'] = True self.module.exit_json(**results) def main(): argument_spec = vmware_argument_spec() argument_spec.update( cluster_name=dict(type='str', required=False), esxi_hostname=dict(type='str', required=False), rules=dict(type='list', default=list(), required=False), ) module = AnsibleModule( argument_spec=argument_spec, required_one_of=[ ['cluster_name', 'esxi_hostname'], ], supports_check_mode=True ) vmware_firewall_manager = VmwareFirewallManager(module) vmware_firewall_manager.ensure() if __name__ == "__main__": main()
closed
ansible/ansible
https://github.com/ansible/ansible
61,332
vmware_host_firewall_manager: TypeError: 'NoneType' object is not subscriptable
##### SUMMARY The function test of `vmware_host_firewall_manager` is currently broken. This seems to be a regression introduced with https://github.com/ansible/ansible/pull/56733. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME vmware_host_firewall_manager ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ``` ##### STEPS TO REPRODUCE The first step of the functional test: https://github.com/ansible/ansible/blob/devel/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml ```yaml - name: Disable the Firewall vvold rule on the ESXi vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: '{{ ccr1 }}' validate_certs: no rules: - name: vvold enabled: False ``` ##### ACTUAL RESULTS ```paste below TASK [vmware_host_firewall_manager : Disable the Firewall vvold rule on the ESXi] **************************************************************** task path: /home/goneri/.ansible/test/tmp/vmware_host_firewall_manager-mn0bxgye-ÅÑŚÌβŁÈ/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml:11 <testhost> ESTABLISH LOCAL CONNECTION FOR USER: goneri <testhost> EXEC /bin/sh -c 'echo ~goneri && sleep 0' <testhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" && echo ansible-tmp-1566836629.9222088-161847597588297="` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" ) && sleep 0' Using module file /home/goneri/git_repos/ansible_projects/b/lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py <testhost> PUT /home/goneri/.ansible/tmp/ansible-local-25543igy5eduv/tmp1tecxld1 TO /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py <testhost> EXEC /bin/sh -c 'chmod u+x /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'ESXI1_HOSTNAME=esxi1.test ESXI1_PASSWORD='"'"'!234AaAa56'"'"' ESXI1_USERNAME=root ESXI2_HOSTNAME=esxi2.test ESXI2_PASSWORD='"'"'!234AaAa56'"'"' ESXI2_USERNAME=root VCENTER_HOSTNAME=vcenter.test VCENTER_PASSWORD='"'"'!234AaAa56'"'"' [email protected] VMWARE_VALIDATE_CERTS=no /home/goneri/git_repos/ansible_projects/b/.virtualenv/py37/bin/python /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'rm -f -r /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 139, in <module> _ansiballz_main() File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 131, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 65, in invoke_module spec.loader.exec_module(module) File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 367, in <module> File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 363, in main File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 238, in ensure TypeError: 'NoneType' object is not subscriptable fatal: [testhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 139, in <module>\n _ansiballz_main()\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 131, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 65, in invoke_module\n spec.loader.exec_module(module)\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 367, in <module>\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 363, in main\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 238, in ensure\nTypeError: 'NoneType' object is not subscriptable\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
https://github.com/ansible/ansible/issues/61332
https://github.com/ansible/ansible/pull/63567
358574d57f2b411e820cbf4d00a8249ac8291cb9
039c770a9539314e2703781d9c42da20ed5904fb
2019-08-26T17:45:19Z
python
2019-10-28T17:01:02Z
test/integration/targets/prepare_vmware_tests/tasks/teardown.yml
--- - name: Remove the VM prepared by prepare_vmware_tests vmware_guest: name: "{{ item.name }}" force: yes state: absent with_items: '{{ virtual_machines + virtual_machines_in_cluster }}' - name: Remove the test_vm* VMs vmware_guest: name: "{{ item }}" force: yes state: absent with_items: - test_vm1 - test_vm2 - test_vm3 - name: Remove the DVSwitch vmware_dvswitch: datacenter_name: '{{ dc1 }}' state: absent switch_name: '{{ item }}' loop: - '{{ dvswitch1 }}' - dvswitch_0001 - dvswitch_0002 ignore_errors: yes - name: Remove the vSwitches vmware_vswitch: hostname: '{{ item }}' username: '{{ esxi_user }}' password: '{{ esxi_password }}' switch_name: "{{ switch1 }}" state: absent with_items: "{{ esxi_hosts }}" ignore_errors: yes - name: Remove ESXi Hosts to vCenter vmware_host: datacenter_name: '{{ dc1 }}' cluster_name: ccr1 esxi_hostname: '{{ item }}' esxi_username: '{{ esxi_user }}' esxi_password: '{{ esxi_password }}' state: absent with_items: "{{ esxi_hosts }}" ignore_errors: yes - name: Umount NFS datastores to ESXi (1/2) vmware_host_datastore: hostname: '{{ item }}' username: '{{ esxi_user }}' password: '{{ esxi_password }}' esxi_hostname: '{{ item }}' # Won't be necessary with https://github.com/ansible/ansible/pull/56516 datastore_name: '{{ ds1 }}' state: absent with_items: "{{ esxi_hosts }}" - name: Umount NFS datastores to ESXi (2/2) vmware_host_datastore: hostname: '{{ item }}' username: '{{ esxi_user }}' password: '{{ esxi_password }}' esxi_hostname: '{{ item }}' # Won't be necessary with https://github.com/ansible/ansible/pull/56516 datastore_name: '{{ ds2 }}' state: absent with_items: "{{ esxi_hosts }}" - name: Delete a datastore cluster to datacenter vmware_datastore_cluster: datacenter_name: "{{ dc1 }}" datastore_cluster_name: '{{ item }}' state: absent with_items: - DSC1 - DSC2 ignore_errors: yes - name: Remove the datacenter vmware_datacenter: datacenter_name: '{{ item }}' state: absent when: vcsim is not defined with_items: - '{{ dc1 }}' - datacenter_0001 - name: kill vcsim uri: url: "http://{{ vcsim }}:5000/killall" when: vcsim is defined
closed
ansible/ansible
https://github.com/ansible/ansible
61,332
vmware_host_firewall_manager: TypeError: 'NoneType' object is not subscriptable
##### SUMMARY The function test of `vmware_host_firewall_manager` is currently broken. This seems to be a regression introduced with https://github.com/ansible/ansible/pull/56733. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME vmware_host_firewall_manager ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below devel ``` ##### STEPS TO REPRODUCE The first step of the functional test: https://github.com/ansible/ansible/blob/devel/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml ```yaml - name: Disable the Firewall vvold rule on the ESXi vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: '{{ ccr1 }}' validate_certs: no rules: - name: vvold enabled: False ``` ##### ACTUAL RESULTS ```paste below TASK [vmware_host_firewall_manager : Disable the Firewall vvold rule on the ESXi] **************************************************************** task path: /home/goneri/.ansible/test/tmp/vmware_host_firewall_manager-mn0bxgye-ÅÑŚÌβŁÈ/test/integration/targets/vmware_host_firewall_manager/tasks/main.yml:11 <testhost> ESTABLISH LOCAL CONNECTION FOR USER: goneri <testhost> EXEC /bin/sh -c 'echo ~goneri && sleep 0' <testhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" && echo ansible-tmp-1566836629.9222088-161847597588297="` echo /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297 `" ) && sleep 0' Using module file /home/goneri/git_repos/ansible_projects/b/lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py <testhost> PUT /home/goneri/.ansible/tmp/ansible-local-25543igy5eduv/tmp1tecxld1 TO /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py <testhost> EXEC /bin/sh -c 'chmod u+x /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'ESXI1_HOSTNAME=esxi1.test ESXI1_PASSWORD='"'"'!234AaAa56'"'"' ESXI1_USERNAME=root ESXI2_HOSTNAME=esxi2.test ESXI2_PASSWORD='"'"'!234AaAa56'"'"' ESXI2_USERNAME=root VCENTER_HOSTNAME=vcenter.test VCENTER_PASSWORD='"'"'!234AaAa56'"'"' [email protected] VMWARE_VALIDATE_CERTS=no /home/goneri/git_repos/ansible_projects/b/.virtualenv/py37/bin/python /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py && sleep 0' <testhost> EXEC /bin/sh -c 'rm -f -r /home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/ > /dev/null 2>&1 && sleep 0' The full traceback is: Traceback (most recent call last): File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 139, in <module> _ansiballz_main() File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 131, in _ansiballz_main invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS) File "/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py", line 65, in invoke_module spec.loader.exec_module(module) File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 367, in <module> File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 363, in main File "/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py", line 238, in ensure TypeError: 'NoneType' object is not subscriptable fatal: [testhost]: FAILED! => { "changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 139, in <module>\n _ansiballz_main()\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 131, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/home/goneri/.ansible/tmp/ansible-tmp-1566836629.9222088-161847597588297/AnsiballZ_vmware_host_firewall_manager.py\", line 65, in invoke_module\n spec.loader.exec_module(module)\n File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 367, in <module>\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 363, in main\n File \"/tmp/ansible_vmware_host_firewall_manager_payload_kf53ugy0/__main__.py\", line 238, in ensure\nTypeError: 'NoneType' object is not subscriptable\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1 } ```
https://github.com/ansible/ansible/issues/61332
https://github.com/ansible/ansible/pull/63567
358574d57f2b411e820cbf4d00a8249ac8291cb9
039c770a9539314e2703781d9c42da20ed5904fb
2019-08-26T17:45:19Z
python
2019-10-28T17:01:02Z
test/integration/targets/vmware_host_firewall_manager/tasks/main.yml
# Test code for the vmware_host_firewall_manager module. # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - when: vcsim is not defined block: - import_role: name: prepare_vmware_tests vars: setup_attach_host: true - name: Disable the Firewall vvold rule on the ESXi vmware_host_firewall_manager: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: '{{ ccr1 }}' validate_certs: no rules: - name: vvold enabled: False - name: Enable vvold rule set on all hosts of {{ ccr1 }} vmware_host_firewall_manager: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no cluster_name: "{{ ccr1 }}" rules: - name: vvold enabled: True register: all_hosts_result - debug: msg="{{ all_hosts_result }}" - name: ensure everything is changed for all hosts of {{ ccr1 }} assert: that: - all_hosts_result.changed - all_hosts_result.rule_set_state is defined - name: ensure info are gathered for all hosts of {{ ccr1 }} assert: that: - all_hosts_result.rule_set_state[item]['vvold']['current_state'] == True - all_hosts_result.rule_set_state[item]['vvold']['desired_state'] == True - all_hosts_result.rule_set_state[item]['vvold']['previous_state'] == False with_items: - '{{ esxi1 }}' - '{{ esxi2 }}' - name: Disable vvold for {{ host1 }} vmware_host_firewall_manager: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no esxi_hostname: '{{ esxi1 }}' rules: - name: vvold enabled: False register: host_result - debug: msg="{{ host_result }}" - name: ensure vvold is disabled for {{ host1 }} assert: that: - host_result.changed - host_result.rule_set_state is defined - name: ensure info are gathered for {{ host1 }} assert: that: - host_result.rule_set_state[item]['vvold']['current_state'] == False - host_result.rule_set_state[item]['vvold']['desired_state'] == False - host_result.rule_set_state[item]['vvold']['previous_state'] == True with_items: - '{{ esxi1 }}' - name: Enable vvold rule set on all hosts of {{ ccr1 }} in check mode vmware_host_firewall_manager: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no cluster_name: "{{ ccr1 }}" rules: - name: vvold enabled: True register: all_hosts_result_check_mode check_mode: yes - debug: var=all_hosts_result_check_mode - name: ensure everything is changed for all hosts of {{ ccr1 }} assert: that: - all_hosts_result_check_mode.changed - all_hosts_result_check_mode.rule_set_state is defined - name: ensure info are gathered for all hosts of {{ ccr1 }} assert: that: - all_hosts_result_check_mode.rule_set_state[esxi1]['vvold']['current_state'] == True - all_hosts_result_check_mode.rule_set_state[esxi2]['vvold']['current_state'] == True - all_hosts_result_check_mode.rule_set_state[esxi2]['vvold']['desired_state'] == True - name: Disable vvold for {{ host1 }} in check mode vmware_host_firewall_manager: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no esxi_hostname: '{{ esxi1 }}' rules: - name: vvold enabled: False register: host_result_check_mode check_mode: yes - debug: msg="{{ host_result_check_mode }}" - name: ensure vvold is disabled for {{ host1 }} assert: that: - host_result_check_mode.changed == False - host_result_check_mode.rule_set_state is defined - name: ensure info are gathered for {{ host1 }} assert: that: - host_result_check_mode.rule_set_state[item]['vvold']['current_state'] == False - host_result_check_mode.rule_set_state[item]['vvold']['desired_state'] == False - host_result_check_mode.rule_set_state[item]['vvold']['previous_state'] == False with_items: - '{{ esxi1 }}' - name: Configure CIMHttpServer rule set on all hosts of {{ ccr1 }} vmware_host_firewall_manager: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no cluster_name: "{{ ccr1 }}" rules: - name: CIMHttpServer enabled: True allowed_hosts: - all_ip: False ip_address: - "192.168.100.11" ip_network: - "192.168.200.0/24" register: all_hosts_ip_specific - debug: var=all_hosts_ip_specific - name: ensure everything is changed for all hosts of {{ ccr1 }} assert: that: - all_hosts_ip_specific.changed - all_hosts_ip_specific.rule_set_state is defined - name: ensure CIMHttpServer is configured for all hosts in {{ ccr1 }} assert: that: - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['current_state'] == True - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['desired_state'] == True - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['previous_state'] == True - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['current_allowed_all'] == False - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['previous_allowed_all'] == True - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['desired_allowed_all'] == False - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['current_allowed_ip'] == ["192.168.100.11"] - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['previous_allowed_ip'] == [] - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['desired_allowed_ip'] == ["192.168.100.11"] - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['current_allowed_networks'] == ["192.168.200.0/24"] - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['previous_allowed_networks'] == [] - all_hosts_ip_specific.rule_set_state[item]['CIMHttpServer']['allowed_hosts']['desired_allowed_networks'] == ["192.168.200.0/24"] with_items: - '{{ esxi1 }}' - '{{ esxi2 }}' - name: Configure the NFC firewall rule to only allow traffic from one IP on one ESXi host vmware_host_firewall_manager: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no esxi_hostname: "{{ esxi1 }}" rules: - name: NFC enabled: True allowed_hosts: - all_ip: False ip_address: - "192.168.100.11" register: single_host_ip_specific - debug: var=single_host_ip_specific - name: ensure NFC is configured on that host assert: that: - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['current_state'] == True - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['desired_state'] == True - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['previous_state'] == True - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['current_allowed_all'] == False - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['previous_allowed_all'] == True - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['desired_allowed_all'] == False - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['current_allowed_ip'] == ["192.168.100.11"] - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['previous_allowed_ip'] == None - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['desired_allowed_ip'] == ["192.168.100.11"] - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['current_allowed_networks'] == [] - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['previous_allowed_networks'] == [] - single_host_ip_specific.rule_set_state[{{ esxi1 }}]['NFC']['allowed_hosts']['desired_allowed_networks'] == []
closed
ansible/ansible
https://github.com/ansible/ansible
63,024
[Docs][Doctoberfest] Update Ansible documentation readme to improve details
<!--- Verify first that your improvement is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below, add suggestions to wording or structure --> Ansible documentation contributors may not be fully familiar with Ansible or git. Update https://github.com/ansible/ansible/blob/devel/docs/docsite/README.md to include details similar to this template: https://github.com/JStickler/doctoberfest/blob/master/doctoberfest/contributor/template_contributor.md Strike a balance so that it doesn't repeat what is already in the "Contributing to the Ansible Documentation page at: - https://docs.ansible.com/ansible/latest/community/documentation_contributions.html <!--- HINT: Did you know the documentation has an "Edit on GitHub" link on every page ? --> ##### ISSUE TYPE - Documentation Report ##### COMPONENT NAME <!--- Write the short name of the rst file, module, plugin, task or feature below, use your best guess if unsure --> ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. OS version, browser, etc. --> ##### ADDITIONAL INFORMATION <!--- Describe how this improves the documentation, e.g. before/after situation or screenshots --> <!--- HINT: You can paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/63024
https://github.com/ansible/ansible/pull/63957
039c770a9539314e2703781d9c42da20ed5904fb
5c962ef859b37ac3a9707a3e1ac88f4b34b78038
2019-10-01T17:47:53Z
python
2019-10-28T17:04:59Z
docs/docsite/README.md
Homepage and Documentation Source for Ansible ============================================= This project hosts the source behind [docs.ansible.com](https://docs.ansible.com/) Contributions to the documentation are welcome. To make changes, submit a pull request that changes the reStructuredText files in the `rst/` directory only, and the core team can do a docs build and push the static files. If you wish to verify output from the markup such as link references, you may install sphinx and build the documentation by running `make webdocs` from the `ansible/docs/docsite` directory. To include module documentation you'll need to run `make webdocs` at the top level of the repository. The generated html files are in `docsite/htmlout/`. To limit module documentation building to a specific module, run `MODULES=NAME make webdocs` instead. This should make testing module documentation syntax much faster. Instead of a single module, you can also specify a comma-separated list of modules. In order to skip building documentation for all modules, specify non-existing module name, for example `MODULES=none make webdocs`. If you do not want to learn the reStructuredText format, you can also [file issues] about documentation problems on the Ansible GitHub project. Note that module documentation can actually be [generated from a DOCUMENTATION docstring][module-docs] in the modules directory, so corrections to modules written as such need to be made in the module source, rather than in docsite source. To install sphinx and the required theme, install ``pip`` and then ``pip install sphinx sphinx_rtd_theme`` [file issues]: https://github.com/ansible/ansible/issues [module-docs]: https://docs.ansible.com/developing_modules.html#documenting-your-module HEADERS ======= RST allows for arbitrary hierarchy for the headers, it will 'learn on the fly'. We also want a standard that all our documents can follow: ``` ########################## # with overline, for parts ########################## ***************************** * with overline, for chapters ***************************** =, for sections =============== -, for subsections ------------------ ^, for sub-subsections ^^^^^^^^^^^^^^^^^^^^^ ", for paragraphs """"""""""""""""" ``` We do have pages littered with ```````` headers, but those should be removed for one of the above.
closed
ansible/ansible
https://github.com/ansible/ansible
62,327
docker_container: remove defaults for various options
##### SUMMARY Various options which reflect container properties have default values. In particular, these are `auto_remove`, `detach`, `init`, `interactive`, `memory`, `paused`, `privileged`, `read_only`, `tty`. While the defaults usually make sense (and coincide with the defaults used by docker), these are highly problematic in situations where not all options affected by a container are specified in `docker_container` usages. For example, when `docker_container` is used with `restart: yes`, and no other options are specified, the container is restarted, **except** if the container uses a non-default value for one of these properties. In that case, the module will recreate the container with no options (except the implicit defaults), which is usually **not** what the user wants. Unfortunately, removing the defaults breaks backwards compatibility. The obvious solution to this, i.e. deprecating the default values (and remove them in four versions, i.e. 2.14) is also not very good, since it will create a *lot* of noise, since in most tasks and playbooks, these options are not specified (and thus the deprecation warning for each of them should be shown). Telling users to disabling warnings for `docker_container` tasks is not a good idea either, especially since in some cases, warnings from docker daemon are passed on. This issue is about discussing this problem and collecting ideas on how this issue can be resolved eventually. Feel free to add any ideas or comments you have! ##### ISSUE TYPE - Feature Idea - Bug Report ##### COMPONENT NAME docker_container ##### ANSIBLE VERSION ``` all ```
https://github.com/ansible/ansible/issues/62327
https://github.com/ansible/ansible/pull/63419
18f4f0549faabefbd0457cde0dd86b0d0fed406b
5c973dd147d2d0bfb2f2affc37664f174eea0a0d
2019-09-15T11:19:55Z
python
2019-10-28T20:40:48Z
changelogs/fragments/63419-docker_container-defaults.yml
closed
ansible/ansible
https://github.com/ansible/ansible
62,327
docker_container: remove defaults for various options
##### SUMMARY Various options which reflect container properties have default values. In particular, these are `auto_remove`, `detach`, `init`, `interactive`, `memory`, `paused`, `privileged`, `read_only`, `tty`. While the defaults usually make sense (and coincide with the defaults used by docker), these are highly problematic in situations where not all options affected by a container are specified in `docker_container` usages. For example, when `docker_container` is used with `restart: yes`, and no other options are specified, the container is restarted, **except** if the container uses a non-default value for one of these properties. In that case, the module will recreate the container with no options (except the implicit defaults), which is usually **not** what the user wants. Unfortunately, removing the defaults breaks backwards compatibility. The obvious solution to this, i.e. deprecating the default values (and remove them in four versions, i.e. 2.14) is also not very good, since it will create a *lot* of noise, since in most tasks and playbooks, these options are not specified (and thus the deprecation warning for each of them should be shown). Telling users to disabling warnings for `docker_container` tasks is not a good idea either, especially since in some cases, warnings from docker daemon are passed on. This issue is about discussing this problem and collecting ideas on how this issue can be resolved eventually. Feel free to add any ideas or comments you have! ##### ISSUE TYPE - Feature Idea - Bug Report ##### COMPONENT NAME docker_container ##### ANSIBLE VERSION ``` all ```
https://github.com/ansible/ansible/issues/62327
https://github.com/ansible/ansible/pull/63419
18f4f0549faabefbd0457cde0dd86b0d0fed406b
5c973dd147d2d0bfb2f2affc37664f174eea0a0d
2019-09-15T11:19:55Z
python
2019-10-28T20:40:48Z
docs/docsite/rst/porting_guides/porting_guide_2.10.rst
.. _porting_2.10_guide: ************************** Ansible 2.10 Porting Guide ************************** This section discusses the behavioral changes between Ansible 2.9 and Ansible 2.10. It is intended to assist in updating your playbooks, plugins and other parts of your Ansible infrastructure so they will work with this version of Ansible. We suggest you read this page along with `Ansible Changelog for 2.10 <https://github.com/ansible/ansible/blob/devel/changelogs/CHANGELOG-v2.10.rst>`_ to understand what updates you may need to make. This document is part of a collection on porting. The complete list of porting guides can be found at :ref:`porting guides <porting_guides>`. .. contents:: Topics Playbook ======== No notable changes Command Line ============ No notable changes Deprecated ========== No notable changes Modules ======= Modules removed --------------- The following modules no longer exist: * letsencrypt use :ref:`acme_certificate <acme_certificate_module>` instead. Deprecation notices ------------------- The following functionality will be removed in Ansible 2.14. Please update update your playbooks accordingly. * The :ref:`openssl_csr <openssl_csr_module>` module's option ``version`` no longer supports values other than ``1`` (the current only standardized CSR version). * :ref:`docker_container <docker_container_module>`: the ``trust_image_content`` option will be removed. It has always been ignored by the module. * :ref:`iam_managed_policy <iam_managed_policy_module>`: the ``fail_on_delete`` option wil be removed. It has always been ignored by the module. * :ref:`s3_lifecycle <s3_lifecycle_module>`: the ``requester_pays`` option will be removed. It has always been ignored by the module. * :ref:`s3_sync <s3_sync_module>`: the ``retries`` option will be removed. It has always been ignored by the module. Noteworthy module changes ------------------------- * :ref:`vmware_datastore_maintenancemode <vmware_datastore_maintenancemode_module>` now returns ``datastore_status`` instead of Ansible internal key ``results``. * :ref:`vmware_host_kernel_manager <vmware_host_kernel_manager_module>` now returns ``host_kernel_status`` instead of Ansible internal key ``results``. * :ref:`vmware_host_ntp <vmware_host_ntp_module>` now returns ``host_ntp_status`` instead of Ansible internal key ``results``. * :ref:`vmware_host_service_manager <vmware_host_service_manager_module>` now returns ``host_service_status`` instead of Ansible internal key ``results``. * :ref:`vmware_tag <vmware_tag_module>` now returns ``tag_status`` instead of Ansible internal key ``results``. * The deprecated ``recurse`` option in :ref:`pacman <pacman_module>` module has been removed, you should use ``extra_args=--recursive`` instead. * :ref:`vmware_guest_custom_attributes <vmware_guest_custom_attributes_module>` module does not require VM name which was a required parameter for releases prior to Ansible 2.10. Plugins ======= No notable changes Porting custom scripts ====================== No notable changes Networking ========== No notable changes
closed
ansible/ansible
https://github.com/ansible/ansible
62,327
docker_container: remove defaults for various options
##### SUMMARY Various options which reflect container properties have default values. In particular, these are `auto_remove`, `detach`, `init`, `interactive`, `memory`, `paused`, `privileged`, `read_only`, `tty`. While the defaults usually make sense (and coincide with the defaults used by docker), these are highly problematic in situations where not all options affected by a container are specified in `docker_container` usages. For example, when `docker_container` is used with `restart: yes`, and no other options are specified, the container is restarted, **except** if the container uses a non-default value for one of these properties. In that case, the module will recreate the container with no options (except the implicit defaults), which is usually **not** what the user wants. Unfortunately, removing the defaults breaks backwards compatibility. The obvious solution to this, i.e. deprecating the default values (and remove them in four versions, i.e. 2.14) is also not very good, since it will create a *lot* of noise, since in most tasks and playbooks, these options are not specified (and thus the deprecation warning for each of them should be shown). Telling users to disabling warnings for `docker_container` tasks is not a good idea either, especially since in some cases, warnings from docker daemon are passed on. This issue is about discussing this problem and collecting ideas on how this issue can be resolved eventually. Feel free to add any ideas or comments you have! ##### ISSUE TYPE - Feature Idea - Bug Report ##### COMPONENT NAME docker_container ##### ANSIBLE VERSION ``` all ```
https://github.com/ansible/ansible/issues/62327
https://github.com/ansible/ansible/pull/63419
18f4f0549faabefbd0457cde0dd86b0d0fed406b
5c973dd147d2d0bfb2f2affc37664f174eea0a0d
2019-09-15T11:19:55Z
python
2019-10-28T20:40:48Z
lib/ansible/modules/cloud/docker/docker_container.py
#!/usr/bin/python # # Copyright 2016 Red Hat | Ansible # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: docker_container short_description: manage docker containers description: - Manage the life cycle of docker containers. - Supports check mode. Run with C(--check) and C(--diff) to view config difference and list of actions to be taken. version_added: "2.1" notes: - For most config changes, the container needs to be recreated, i.e. the existing container has to be destroyed and a new one created. This can cause unexpected data loss and downtime. You can use the I(comparisons) option to prevent this. - If the module needs to recreate the container, it will only use the options provided to the module to create the new container (except I(image)). Therefore, always specify *all* options relevant to the container. - When I(restart) is set to C(true), the module will only restart the container if no config changes are detected. Please note that several options have default values; if the container to be restarted uses different values for these options, it will be recreated instead. The options with default values which can cause this are I(auto_remove), I(detach), I(init), I(interactive), I(memory), I(paused), I(privileged), I(read_only) and I(tty). options: auto_remove: description: - Enable auto-removal of the container on daemon side when the container's process exits. type: bool default: no version_added: "2.4" blkio_weight: description: - Block IO (relative weight), between 10 and 1000. type: int capabilities: description: - List of capabilities to add to the container. type: list elements: str cap_drop: description: - List of capabilities to drop from the container. type: list elements: str version_added: "2.7" cleanup: description: - Use with I(detach=false) to remove the container after successful execution. type: bool default: no version_added: "2.2" command: description: - Command to execute when the container starts. A command may be either a string or a list. - Prior to version 2.4, strings were split on commas. type: raw comparisons: description: - Allows to specify how properties of existing containers are compared with module options to decide whether the container should be recreated / updated or not. - Only options which correspond to the state of a container as handled by the Docker daemon can be specified, as well as C(networks). - Must be a dictionary specifying for an option one of the keys C(strict), C(ignore) and C(allow_more_present). - If C(strict) is specified, values are tested for equality, and changes always result in updating or restarting. If C(ignore) is specified, changes are ignored. - C(allow_more_present) is allowed only for lists, sets and dicts. If it is specified for lists or sets, the container will only be updated or restarted if the module option contains a value which is not present in the container's options. If the option is specified for a dict, the container will only be updated or restarted if the module option contains a key which isn't present in the container's option, or if the value of a key present differs. - The wildcard option C(*) can be used to set one of the default values C(strict) or C(ignore) to *all* comparisons which are not explicitly set to other values. - See the examples for details. type: dict version_added: "2.8" cpu_period: description: - Limit CPU CFS (Completely Fair Scheduler) period. type: int cpu_quota: description: - Limit CPU CFS (Completely Fair Scheduler) quota. type: int cpuset_cpus: description: - CPUs in which to allow execution C(1,3) or C(1-3). type: str cpuset_mems: description: - Memory nodes (MEMs) in which to allow execution C(0-3) or C(0,1). type: str cpu_shares: description: - CPU shares (relative weight). type: int detach: description: - Enable detached mode to leave the container running in background. - If disabled, the task will reflect the status of the container run (failed if the command failed). type: bool default: yes devices: description: - List of host device bindings to add to the container. - "Each binding is a mapping expressed in the format C(<path_on_host>:<path_in_container>:<cgroup_permissions>)." type: list elements: str device_read_bps: description: - "List of device path and read rate (bytes per second) from device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit in format C(<number>[<unit>])." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str required: yes version_added: "2.8" device_write_bps: description: - "List of device and write rate (bytes per second) to device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit in format C(<number>[<unit>])." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str required: yes version_added: "2.8" device_read_iops: description: - "List of device and read rate (IO per second) from device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit." - "Must be a positive integer." type: int required: yes version_added: "2.8" device_write_iops: description: - "List of device and write rate (IO per second) to device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit." - "Must be a positive integer." type: int required: yes version_added: "2.8" dns_opts: description: - List of DNS options. type: list elements: str dns_servers: description: - List of custom DNS servers. type: list elements: str dns_search_domains: description: - List of custom DNS search domains. type: list elements: str domainname: description: - Container domainname. type: str version_added: "2.5" env: description: - Dictionary of key,value pairs. - Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (e.g. C("true")) in order to avoid data loss. type: dict env_file: description: - Path to a file, present on the target, containing environment variables I(FOO=BAR). - If variable also present in I(env), then the I(env) value will override. type: path version_added: "2.2" entrypoint: description: - Command that overwrites the default C(ENTRYPOINT) of the image. type: list elements: str etc_hosts: description: - Dict of host-to-IP mappings, where each host name is a key in the dictionary. Each host name will be added to the container's C(/etc/hosts) file. type: dict exposed_ports: description: - List of additional container ports which informs Docker that the container listens on the specified network ports at runtime. - If the port is already exposed using C(EXPOSE) in a Dockerfile, it does not need to be exposed again. type: list elements: str aliases: - exposed - expose force_kill: description: - Use the kill command when stopping a running container. type: bool default: no aliases: - forcekill groups: description: - List of additional group names and/or IDs that the container process will run as. type: list elements: str healthcheck: description: - Configure a check that is run to determine whether or not containers for this service are "healthy". - "See the docs for the L(HEALTHCHECK Dockerfile instruction,https://docs.docker.com/engine/reference/builder/#healthcheck) for details on how healthchecks work." - "I(interval), I(timeout) and I(start_period) are specified as durations. They accept duration as a string in a format that look like: C(5h34m56s), C(1m30s) etc. The supported units are C(us), C(ms), C(s), C(m) and C(h)." type: dict suboptions: test: description: - Command to run to check health. - Must be either a string or a list. If it is a list, the first item must be one of C(NONE), C(CMD) or C(CMD-SHELL). type: raw interval: description: - Time between running the check. - The default used by the Docker daemon is C(30s). type: str timeout: description: - Maximum time to allow one check to run. - The default used by the Docker daemon is C(30s). type: str retries: description: - Consecutive number of failures needed to report unhealthy. - The default used by the Docker daemon is C(3). type: int start_period: description: - Start period for the container to initialize before starting health-retries countdown. - The default used by the Docker daemon is C(0s). type: str version_added: "2.8" hostname: description: - The container's hostname. type: str ignore_image: description: - When I(state) is C(present) or C(started), the module compares the configuration of an existing container to requested configuration. The evaluation includes the image version. If the image version in the registry does not match the container, the container will be recreated. You can stop this behavior by setting I(ignore_image) to C(True). - "*Warning:* This option is ignored if C(image: ignore) or C(*: ignore) is specified in the I(comparisons) option." type: bool default: no version_added: "2.2" image: description: - Repository path and tag used to create the container. If an image is not found or pull is true, the image will be pulled from the registry. If no tag is included, C(latest) will be used. - Can also be an image ID. If this is the case, the image is assumed to be available locally. The I(pull) option is ignored for this case. type: str init: description: - Run an init inside the container that forwards signals and reaps processes. - This option requires Docker API >= 1.25. type: bool default: no version_added: "2.6" interactive: description: - Keep stdin open after a container is launched, even if not attached. type: bool default: no ipc_mode: description: - Set the IPC mode for the container. - Can be one of C(container:<name|id>) to reuse another container's IPC namespace or C(host) to use the host's IPC namespace within the container. type: str keep_volumes: description: - Retain volumes associated with a removed container. type: bool default: yes kill_signal: description: - Override default signal used to kill a running container. type: str kernel_memory: description: - "Kernel memory limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte). Minimum is C(4M)." - Omitting the unit defaults to bytes. type: str labels: description: - Dictionary of key value pairs. type: dict links: description: - List of name aliases for linked containers in the format C(container_name:alias). - Setting this will force container to be restarted. type: list elements: str log_driver: description: - Specify the logging driver. Docker uses C(json-file) by default. - See L(here,https://docs.docker.com/config/containers/logging/configure/) for possible choices. type: str log_options: description: - Dictionary of options specific to the chosen I(log_driver). - See U(https://docs.docker.com/engine/admin/logging/overview/) for details. type: dict aliases: - log_opt mac_address: description: - Container MAC address (e.g. 92:d0:c6:0a:29:33). type: str memory: description: - "Memory limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. type: str default: '0' memory_reservation: description: - "Memory soft limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. type: str memory_swap: description: - "Total memory limit (memory + swap) in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. type: str memory_swappiness: description: - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. - If not set, the value will be remain the same if container exists and will be inherited from the host machine if it is (re-)created. type: int mounts: version_added: "2.9" type: list elements: dict description: - Specification for mounts to be added to the container. More powerful alternative to I(volumes). suboptions: target: description: - Path inside the container. type: str required: true source: description: - Mount source (e.g. a volume name or a host path). type: str type: description: - The mount type. - Note that C(npipe) is only supported by Docker for Windows. type: str choices: - bind - npipe - tmpfs - volume default: volume read_only: description: - Whether the mount should be read-only. type: bool consistency: description: - The consistency requirement for the mount. type: str choices: - cached - consistent - default - delegated propagation: description: - Propagation mode. Only valid for the C(bind) type. type: str choices: - private - rprivate - shared - rshared - slave - rslave no_copy: description: - False if the volume should be populated with the data from the target. Only valid for the C(volume) type. - The default value is C(false). type: bool labels: description: - User-defined name and labels for the volume. Only valid for the C(volume) type. type: dict volume_driver: description: - Specify the volume driver. Only valid for the C(volume) type. - See L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details. type: str volume_options: description: - Dictionary of options specific to the chosen volume_driver. See L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details. type: dict tmpfs_size: description: - "The size for the tmpfs mount in bytes in format <number>[<unit>]." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str tmpfs_mode: description: - The permission mode for the tmpfs mount. type: str name: description: - Assign a name to a new container or match an existing container. - When identifying an existing container name may be a name or a long or short container ID. type: str required: yes network_mode: description: - Connect the container to a network. Choices are C(bridge), C(host), C(none) or C(container:<name|id>). type: str userns_mode: description: - Set the user namespace mode for the container. Currently, the only valid value are C(host) and the empty string. type: str version_added: "2.5" networks: description: - List of networks the container belongs to. - For examples of the data structure and usage see EXAMPLES below. - To remove a container from one or more networks, use the I(purge_networks) option. - Note that as opposed to C(docker run ...), M(docker_container) does not remove the default network if I(networks) is specified. You need to explicitly use I(purge_networks) to enforce the removal of the default network (and all other networks not explicitly mentioned in I(networks)). Alternatively, use the I(networks_cli_compatible) option, which will be enabled by default from Ansible 2.12 on. type: list elements: dict suboptions: name: description: - The network's name. type: str required: yes ipv4_address: description: - The container's IPv4 address in this network. type: str ipv6_address: description: - The container's IPv6 address in this network. type: str links: description: - A list of containers to link to. type: list elements: str aliases: description: - List of aliases for this container in this network. These names can be used in the network to reach this container. type: list elements: str version_added: "2.2" networks_cli_compatible: description: - "When networks are provided to the module via the I(networks) option, the module behaves differently than C(docker run --network): C(docker run --network other) will create a container with network C(other) attached, but the default network not attached. This module with I(networks: {name: other}) will create a container with both C(default) and C(other) attached. If I(purge_networks) is set to C(yes), the C(default) network will be removed afterwards." - "If I(networks_cli_compatible) is set to C(yes), this module will behave as C(docker run --network) and will *not* add the default network if I(networks) is specified. If I(networks) is not specified, the default network will be attached." - "Note that docker CLI also sets I(network_mode) to the name of the first network added if C(--network) is specified. For more compatibility with docker CLI, you explicitly have to set I(network_mode) to the name of the first network you're adding." - Current value is C(no). A new default of C(yes) will be set in Ansible 2.12. type: bool version_added: "2.8" oom_killer: description: - Whether or not to disable OOM Killer for the container. type: bool oom_score_adj: description: - An integer value containing the score given to the container in order to tune OOM killer preferences. type: int version_added: "2.2" output_logs: description: - If set to true, output of the container command will be printed. - Only effective when I(log_driver) is set to C(json-file) or C(journald). type: bool default: no version_added: "2.7" paused: description: - Use with the started state to pause running processes inside the container. type: bool default: no pid_mode: description: - Set the PID namespace mode for the container. - Note that Docker SDK for Python < 2.0 only supports C(host). Newer versions of the Docker SDK for Python (docker) allow all values supported by the Docker daemon. type: str pids_limit: description: - Set PIDs limit for the container. It accepts an integer value. - Set C(-1) for unlimited PIDs. type: int version_added: "2.8" privileged: description: - Give extended privileges to the container. type: bool default: no published_ports: description: - List of ports to publish from the container to the host. - "Use docker CLI syntax: C(8000), C(9000:8000), or C(0.0.0.0:9000:8000), where 8000 is a container port, 9000 is a host port, and 0.0.0.0 is a host interface." - Port ranges can be used for source and destination ports. If two ranges with different lengths are specified, the shorter range will be used. - "Bind addresses must be either IPv4 or IPv6 addresses. Hostnames are *not* allowed. This is different from the C(docker) command line utility. Use the L(dig lookup,../lookup/dig.html) to resolve hostnames." - A value of C(all) will publish all exposed container ports to random host ports, ignoring any other mappings. - If I(networks) parameter is provided, will inspect each network to see if there exists a bridge network with optional parameter C(com.docker.network.bridge.host_binding_ipv4). If such a network is found, then published ports where no host IP address is specified will be bound to the host IP pointed to by C(com.docker.network.bridge.host_binding_ipv4). Note that the first bridge network with a C(com.docker.network.bridge.host_binding_ipv4) value encountered in the list of I(networks) is the one that will be used. type: list elements: str aliases: - ports pull: description: - If true, always pull the latest version of an image. Otherwise, will only pull an image when missing. - "*Note:* images are only pulled when specified by name. If the image is specified as a image ID (hash), it cannot be pulled." type: bool default: no purge_networks: description: - Remove the container from ALL networks not included in I(networks) parameter. - Any default networks such as C(bridge), if not found in I(networks), will be removed as well. type: bool default: no version_added: "2.2" read_only: description: - Mount the container's root file system as read-only. type: bool default: no recreate: description: - Use with present and started states to force the re-creation of an existing container. type: bool default: no restart: description: - Use with started state to force a matching container to be stopped and restarted. type: bool default: no restart_policy: description: - Container restart policy. - Place quotes around C(no) option. type: str choices: - 'no' - 'on-failure' - 'always' - 'unless-stopped' restart_retries: description: - Use with restart policy to control maximum number of restart attempts. type: int runtime: description: - Runtime to use for the container. type: str version_added: "2.8" shm_size: description: - "Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses C(64M). type: str security_opts: description: - List of security options in the form of C("label:user:User"). type: list elements: str state: description: - 'C(absent) - A container matching the specified name will be stopped and removed. Use I(force_kill) to kill the container rather than stopping it. Use I(keep_volumes) to retain volumes associated with the removed container.' - 'C(present) - Asserts the existence of a container matching the name and any provided configuration parameters. If no container matches the name, a container will be created. If a container matches the name but the provided configuration does not match, the container will be updated, if it can be. If it cannot be updated, it will be removed and re-created with the requested config.' - 'C(started) - Asserts that the container is first C(present), and then if the container is not running moves it to a running state. Use I(restart) to force a matching container to be stopped and restarted.' - 'C(stopped) - Asserts that the container is first C(present), and then if the container is running moves it to a stopped state.' - To control what will be taken into account when comparing configuration, see the I(comparisons) option. To avoid that the image version will be taken into account, you can also use the I(ignore_image) option. - Use the I(recreate) option to always force re-creation of a matching container, even if it is running. - If the container should be killed instead of stopped in case it needs to be stopped for recreation, or because I(state) is C(stopped), please use the I(force_kill) option. Use I(keep_volumes) to retain volumes associated with a removed container. - Use I(keep_volumes) to retain volumes associated with a removed container. type: str default: started choices: - absent - present - stopped - started stop_signal: description: - Override default signal used to stop the container. type: str stop_timeout: description: - Number of seconds to wait for the container to stop before sending C(SIGKILL). When the container is created by this module, its C(StopTimeout) configuration will be set to this value. - When the container is stopped, will be used as a timeout for stopping the container. In case the container has a custom C(StopTimeout) configuration, the behavior depends on the version of the docker daemon. New versions of the docker daemon will always use the container's configured C(StopTimeout) value if it has been configured. type: int trust_image_content: description: - If C(yes), skip image verification. - The option has never been used by the module. It will be removed in Ansible 2.14. type: bool default: no tmpfs: description: - Mount a tmpfs directory. type: list elements: str version_added: 2.4 tty: description: - Allocate a pseudo-TTY. type: bool default: no ulimits: description: - "List of ulimit options. A ulimit is specified as C(nofile:262144:262144)." type: list elements: str sysctls: description: - Dictionary of key,value pairs. type: dict version_added: 2.4 user: description: - Sets the username or UID used and optionally the groupname or GID for the specified command. - "Can be of the forms C(user), C(user:group), C(uid), C(uid:gid), C(user:gid) or C(uid:group)." type: str uts: description: - Set the UTS namespace mode for the container. type: str volumes: description: - List of volumes to mount within the container. - "Use docker CLI-style syntax: C(/host:/container[:mode])" - "Mount modes can be a comma-separated list of various modes such as C(ro), C(rw), C(consistent), C(delegated), C(cached), C(rprivate), C(private), C(rshared), C(shared), C(rslave), C(slave), and C(nocopy). Note that the docker daemon might not support all modes and combinations of such modes." - SELinux hosts can additionally use C(z) or C(Z) to use a shared or private label for the volume. - "Note that Ansible 2.7 and earlier only supported one mode, which had to be one of C(ro), C(rw), C(z), and C(Z)." type: list elements: str volume_driver: description: - The container volume driver. type: str volumes_from: description: - List of container names or IDs to get volumes from. type: list elements: str working_dir: description: - Path to the working directory. type: str version_added: "2.4" extends_documentation_fragment: - docker - docker.docker_py_1_documentation author: - "Cove Schneider (@cove)" - "Joshua Conner (@joshuaconner)" - "Pavel Antonov (@softzilla)" - "Thomas Steinbach (@ThomasSteinbach)" - "Philippe Jandot (@zfil)" - "Daan Oosterveld (@dusdanig)" - "Chris Houseknecht (@chouseknecht)" - "Kassian Sun (@kassiansun)" - "Felix Fontein (@felixfontein)" requirements: - "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 1.8.0 (use L(docker-py,https://pypi.org/project/docker-py/) for Python 2.6)" - "Docker API >= 1.20" ''' EXAMPLES = ''' - name: Create a data container docker_container: name: mydata image: busybox volumes: - /data - name: Re-create a redis container docker_container: name: myredis image: redis command: redis-server --appendonly yes state: present recreate: yes exposed_ports: - 6379 volumes_from: - mydata - name: Restart a container docker_container: name: myapplication image: someuser/appimage state: started restart: yes links: - "myredis:aliasedredis" devices: - "/dev/sda:/dev/xvda:rwm" ports: - "8080:9000" - "127.0.0.1:8081:9001/udp" env: SECRET_KEY: "ssssh" # Values which might be parsed as numbers, booleans or other types by the YAML parser need to be quoted BOOLEAN_KEY: "yes" - name: Container present docker_container: name: mycontainer state: present image: ubuntu:14.04 command: sleep infinity - name: Stop a container docker_container: name: mycontainer state: stopped - name: Start 4 load-balanced containers docker_container: name: "container{{ item }}" recreate: yes image: someuser/anotherappimage command: sleep 1d with_sequence: count=4 - name: remove container docker_container: name: ohno state: absent - name: Syslogging output docker_container: name: myservice image: busybox log_driver: syslog log_options: syslog-address: tcp://my-syslog-server:514 syslog-facility: daemon # NOTE: in Docker 1.13+ the "syslog-tag" option was renamed to "tag" for # older docker installs, use "syslog-tag" instead tag: myservice - name: Create db container and connect to network docker_container: name: db_test image: "postgres:latest" networks: - name: "{{ docker_network_name }}" - name: Start container, connect to network and link docker_container: name: sleeper image: ubuntu:14.04 networks: - name: TestingNet ipv4_address: "172.1.1.100" aliases: - sleepyzz links: - db_test:db - name: TestingNet2 - name: Start a container with a command docker_container: name: sleepy image: ubuntu:14.04 command: ["sleep", "infinity"] - name: Add container to networks docker_container: name: sleepy networks: - name: TestingNet ipv4_address: 172.1.1.18 links: - sleeper - name: TestingNet2 ipv4_address: 172.1.10.20 - name: Update network with aliases docker_container: name: sleepy networks: - name: TestingNet aliases: - sleepyz - zzzz - name: Remove container from one network docker_container: name: sleepy networks: - name: TestingNet2 purge_networks: yes - name: Remove container from all networks docker_container: name: sleepy purge_networks: yes - name: Start a container and use an env file docker_container: name: agent image: jenkinsci/ssh-slave env_file: /var/tmp/jenkins/agent.env - name: Create a container with limited capabilities docker_container: name: sleepy image: ubuntu:16.04 command: sleep infinity capabilities: - sys_time cap_drop: - all - name: Finer container restart/update control docker_container: name: test image: ubuntu:18.04 env: arg1: "true" arg2: "whatever" volumes: - /tmp:/tmp comparisons: image: ignore # don't restart containers with older versions of the image env: strict # we want precisely this environment volumes: allow_more_present # if there are more volumes, that's ok, as long as `/tmp:/tmp` is there - name: Finer container restart/update control II docker_container: name: test image: ubuntu:18.04 env: arg1: "true" arg2: "whatever" comparisons: '*': ignore # by default, ignore *all* options (including image) env: strict # except for environment variables; there, we want to be strict - name: Start container with healthstatus docker_container: name: nginx-proxy image: nginx:1.13 state: started healthcheck: # Check if nginx server is healthy by curl'ing the server. # If this fails or timeouts, the healthcheck fails. test: ["CMD", "curl", "--fail", "http://nginx.host.com"] interval: 1m30s timeout: 10s retries: 3 start_period: 30s - name: Remove healthcheck from container docker_container: name: nginx-proxy image: nginx:1.13 state: started healthcheck: # The "NONE" check needs to be specified test: ["NONE"] - name: start container with block device read limit docker_container: name: test image: ubuntu:18.04 state: started device_read_bps: # Limit read rate for /dev/sda to 20 mebibytes per second - path: /dev/sda rate: 20M device_read_iops: # Limit read rate for /dev/sdb to 300 IO per second - path: /dev/sdb rate: 300 ''' RETURN = ''' container: description: - Facts representing the current state of the container. Matches the docker inspection output. - Note that facts are part of the registered vars since Ansible 2.8. For compatibility reasons, the facts are also accessible directly as C(docker_container). Note that the returned fact will be removed in Ansible 2.12. - Before 2.3 this was C(ansible_docker_container) but was renamed in 2.3 to C(docker_container) due to conflicts with the connection plugin. - Empty if I(state) is C(absent) - If I(detached) is C(false), will include C(Output) attribute containing any output from container run. returned: always type: dict sample: '{ "AppArmorProfile": "", "Args": [], "Config": { "AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": [ "/usr/bin/supervisord" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": { "443/tcp": {}, "80/tcp": {} }, "Hostname": "8e47bf643eb9", "Image": "lnmp_nginx:v1", "Labels": {}, "OnBuild": null, "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": { "/tmp/lnmp/nginx-sites/logs/": {} }, ... }' ''' import os import re import shlex import traceback from distutils.version import LooseVersion from ansible.module_utils.common.text.formatters import human_to_bytes from ansible.module_utils.docker.common import ( AnsibleDockerClient, DifferenceTracker, DockerBaseClass, compare_generic, is_image_name_id, sanitize_result, clean_dict_booleans_for_docker_api, omit_none_from_dict, parse_healthcheck, DOCKER_COMMON_ARGS, RequestException, ) from ansible.module_utils.six import string_types try: from docker import utils from ansible.module_utils.docker.common import docker_version if LooseVersion(docker_version) >= LooseVersion('1.10.0'): from docker.types import Ulimit, LogConfig from docker import types as docker_types else: from docker.utils.types import Ulimit, LogConfig from docker.errors import DockerException, APIError, NotFound except Exception: # missing Docker SDK for Python handled in ansible.module_utils.docker.common pass REQUIRES_CONVERSION_TO_BYTES = [ 'kernel_memory', 'memory', 'memory_reservation', 'memory_swap', 'shm_size' ] def is_volume_permissions(mode): for part in mode.split(','): if part not in ('rw', 'ro', 'z', 'Z', 'consistent', 'delegated', 'cached', 'rprivate', 'private', 'rshared', 'shared', 'rslave', 'slave', 'nocopy'): return False return True def parse_port_range(range_or_port, client): ''' Parses a string containing either a single port or a range of ports. Returns a list of integers for each port in the list. ''' if '-' in range_or_port: try: start, end = [int(port) for port in range_or_port.split('-')] except Exception: client.fail('Invalid port range: "{0}"'.format(range_or_port)) if end < start: client.fail('Invalid port range: "{0}"'.format(range_or_port)) return list(range(start, end + 1)) else: try: return [int(range_or_port)] except Exception: client.fail('Invalid port: "{0}"'.format(range_or_port)) def split_colon_ipv6(text, client): ''' Split string by ':', while keeping IPv6 addresses in square brackets in one component. ''' if '[' not in text: return text.split(':') start = 0 result = [] while start < len(text): i = text.find('[', start) if i < 0: result.extend(text[start:].split(':')) break j = text.find(']', i) if j < 0: client.fail('Cannot find closing "]" in input "{0}" for opening "[" at index {1}!'.format(text, i + 1)) result.extend(text[start:i].split(':')) k = text.find(':', j) if k < 0: result[-1] += text[i:] start = len(text) else: result[-1] += text[i:k] if k == len(text): result.append('') break start = k + 1 return result class TaskParameters(DockerBaseClass): ''' Access and parse module parameters ''' def __init__(self, client): super(TaskParameters, self).__init__() self.client = client self.auto_remove = None self.blkio_weight = None self.capabilities = None self.cap_drop = None self.cleanup = None self.command = None self.cpu_period = None self.cpu_quota = None self.cpuset_cpus = None self.cpuset_mems = None self.cpu_shares = None self.detach = None self.debug = None self.devices = None self.device_read_bps = None self.device_write_bps = None self.device_read_iops = None self.device_write_iops = None self.dns_servers = None self.dns_opts = None self.dns_search_domains = None self.domainname = None self.env = None self.env_file = None self.entrypoint = None self.etc_hosts = None self.exposed_ports = None self.force_kill = None self.groups = None self.healthcheck = None self.hostname = None self.ignore_image = None self.image = None self.init = None self.interactive = None self.ipc_mode = None self.keep_volumes = None self.kernel_memory = None self.kill_signal = None self.labels = None self.links = None self.log_driver = None self.output_logs = None self.log_options = None self.mac_address = None self.memory = None self.memory_reservation = None self.memory_swap = None self.memory_swappiness = None self.mounts = None self.name = None self.network_mode = None self.userns_mode = None self.networks = None self.networks_cli_compatible = None self.oom_killer = None self.oom_score_adj = None self.paused = None self.pid_mode = None self.pids_limit = None self.privileged = None self.purge_networks = None self.pull = None self.read_only = None self.recreate = None self.restart = None self.restart_retries = None self.restart_policy = None self.runtime = None self.shm_size = None self.security_opts = None self.state = None self.stop_signal = None self.stop_timeout = None self.tmpfs = None self.trust_image_content = None self.tty = None self.user = None self.uts = None self.volumes = None self.volume_binds = dict() self.volumes_from = None self.volume_driver = None self.working_dir = None for key, value in client.module.params.items(): setattr(self, key, value) self.comparisons = client.comparisons # If state is 'absent', parameters do not have to be parsed or interpreted. # Only the container's name is needed. if self.state == 'absent': return if self.groups: # In case integers are passed as groups, we need to convert them to # strings as docker internally treats them as strings. self.groups = [str(g) for g in self.groups] for param_name in REQUIRES_CONVERSION_TO_BYTES: if client.module.params.get(param_name): try: setattr(self, param_name, human_to_bytes(client.module.params.get(param_name))) except ValueError as exc: self.fail("Failed to convert %s to bytes: %s" % (param_name, exc)) self.publish_all_ports = False self.published_ports = self._parse_publish_ports() if self.published_ports in ('all', 'ALL'): self.publish_all_ports = True self.published_ports = None self.ports = self._parse_exposed_ports(self.published_ports) self.log("expose ports:") self.log(self.ports, pretty_print=True) self.links = self._parse_links(self.links) if self.volumes: self.volumes = self._expand_host_paths() self.tmpfs = self._parse_tmpfs() self.env = self._get_environment() self.ulimits = self._parse_ulimits() self.sysctls = self._parse_sysctls() self.log_config = self._parse_log_config() try: self.healthcheck, self.disable_healthcheck = parse_healthcheck(self.healthcheck) except ValueError as e: self.fail(str(e)) self.exp_links = None self.volume_binds = self._get_volume_binds(self.volumes) self.pid_mode = self._replace_container_names(self.pid_mode) self.ipc_mode = self._replace_container_names(self.ipc_mode) self.network_mode = self._replace_container_names(self.network_mode) self.log("volumes:") self.log(self.volumes, pretty_print=True) self.log("volume binds:") self.log(self.volume_binds, pretty_print=True) if self.networks: for network in self.networks: network['id'] = self._get_network_id(network['name']) if not network['id']: self.fail("Parameter error: network named %s could not be found. Does it exist?" % network['name']) if network.get('links'): network['links'] = self._parse_links(network['links']) if self.mac_address: # Ensure the MAC address uses colons instead of hyphens for later comparison self.mac_address = self.mac_address.replace('-', ':') if self.entrypoint: # convert from list to str. self.entrypoint = ' '.join([str(x) for x in self.entrypoint]) if self.command: # convert from list to str if isinstance(self.command, list): self.command = ' '.join([str(x) for x in self.command]) self.mounts_opt, self.expected_mounts = self._process_mounts() self._check_mount_target_collisions() for param_name in ["device_read_bps", "device_write_bps"]: if client.module.params.get(param_name): self._process_rate_bps(option=param_name) for param_name in ["device_read_iops", "device_write_iops"]: if client.module.params.get(param_name): self._process_rate_iops(option=param_name) def fail(self, msg): self.client.fail(msg) @property def update_parameters(self): ''' Returns parameters used to update a container ''' update_parameters = dict( blkio_weight='blkio_weight', cpu_period='cpu_period', cpu_quota='cpu_quota', cpu_shares='cpu_shares', cpuset_cpus='cpuset_cpus', cpuset_mems='cpuset_mems', mem_limit='memory', mem_reservation='memory_reservation', memswap_limit='memory_swap', kernel_memory='kernel_memory', ) result = dict() for key, value in update_parameters.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: result[key] = getattr(self, value) return result @property def create_parameters(self): ''' Returns parameters used to create a container ''' create_params = dict( command='command', domainname='domainname', hostname='hostname', user='user', detach='detach', stdin_open='interactive', tty='tty', ports='ports', environment='env', name='name', entrypoint='entrypoint', mac_address='mac_address', labels='labels', stop_signal='stop_signal', working_dir='working_dir', stop_timeout='stop_timeout', healthcheck='healthcheck', ) if self.client.docker_py_version < LooseVersion('3.0'): # cpu_shares and volume_driver moved to create_host_config in > 3 create_params['cpu_shares'] = 'cpu_shares' create_params['volume_driver'] = 'volume_driver' result = dict( host_config=self._host_config(), volumes=self._get_mounts(), ) for key, value in create_params.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: result[key] = getattr(self, value) if self.networks_cli_compatible and self.networks: network = self.networks[0] params = dict() for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'): if network.get(para): params[para] = network[para] network_config = dict() network_config[network['name']] = self.client.create_endpoint_config(**params) result['networking_config'] = self.client.create_networking_config(network_config) return result def _expand_host_paths(self): new_vols = [] for vol in self.volumes: if ':' in vol: if len(vol.split(':')) == 3: host, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if re.match(r'[.~]', host): host = os.path.abspath(os.path.expanduser(host)) new_vols.append("%s:%s:%s" % (host, container, mode)) continue elif len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]) and re.match(r'[.~]', parts[0]): host = os.path.abspath(os.path.expanduser(parts[0])) new_vols.append("%s:%s:rw" % (host, parts[1])) continue new_vols.append(vol) return new_vols def _get_mounts(self): ''' Return a list of container mounts. :return: ''' result = [] if self.volumes: for vol in self.volumes: if ':' in vol: if len(vol.split(':')) == 3: dummy, container, dummy = vol.split(':') result.append(container) continue if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): result.append(parts[1]) continue result.append(vol) self.log("mounts:") self.log(result, pretty_print=True) return result def _host_config(self): ''' Returns parameters used to create a HostConfig object ''' host_config_params = dict( port_bindings='published_ports', publish_all_ports='publish_all_ports', links='links', privileged='privileged', dns='dns_servers', dns_opt='dns_opts', dns_search='dns_search_domains', binds='volume_binds', volumes_from='volumes_from', network_mode='network_mode', userns_mode='userns_mode', cap_add='capabilities', cap_drop='cap_drop', extra_hosts='etc_hosts', read_only='read_only', ipc_mode='ipc_mode', security_opt='security_opts', ulimits='ulimits', sysctls='sysctls', log_config='log_config', mem_limit='memory', memswap_limit='memory_swap', mem_swappiness='memory_swappiness', oom_score_adj='oom_score_adj', oom_kill_disable='oom_killer', shm_size='shm_size', group_add='groups', devices='devices', pid_mode='pid_mode', tmpfs='tmpfs', init='init', uts_mode='uts', runtime='runtime', auto_remove='auto_remove', device_read_bps='device_read_bps', device_write_bps='device_write_bps', device_read_iops='device_read_iops', device_write_iops='device_write_iops', pids_limit='pids_limit', mounts='mounts', ) if self.client.docker_py_version >= LooseVersion('1.9') and self.client.docker_api_version >= LooseVersion('1.22'): # blkio_weight can always be updated, but can only be set on creation # when Docker SDK for Python and Docker API are new enough host_config_params['blkio_weight'] = 'blkio_weight' if self.client.docker_py_version >= LooseVersion('3.0'): # cpu_shares and volume_driver moved to create_host_config in > 3 host_config_params['cpu_shares'] = 'cpu_shares' host_config_params['volume_driver'] = 'volume_driver' params = dict() for key, value in host_config_params.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: params[key] = getattr(self, value) if self.restart_policy: params['restart_policy'] = dict(Name=self.restart_policy, MaximumRetryCount=self.restart_retries) if 'mounts' in params: params['mounts'] = self.mounts_opt return self.client.create_host_config(**params) @property def default_host_ip(self): ip = '0.0.0.0' if not self.networks: return ip for net in self.networks: if net.get('name'): try: network = self.client.inspect_network(net['name']) if network.get('Driver') == 'bridge' and \ network.get('Options', {}).get('com.docker.network.bridge.host_binding_ipv4'): ip = network['Options']['com.docker.network.bridge.host_binding_ipv4'] break except NotFound as nfe: self.client.fail( "Cannot inspect the network '{0}' to determine the default IP: {1}".format(net['name'], nfe), exception=traceback.format_exc() ) return ip def _parse_publish_ports(self): ''' Parse ports from docker CLI syntax ''' if self.published_ports is None: return None if 'all' in self.published_ports: return 'all' default_ip = self.default_host_ip binds = {} for port in self.published_ports: parts = split_colon_ipv6(str(port), self.client) container_port = parts[-1] protocol = '' if '/' in container_port: container_port, protocol = parts[-1].split('/') container_ports = parse_port_range(container_port, self.client) p_len = len(parts) if p_len == 1: port_binds = len(container_ports) * [(default_ip,)] elif p_len == 2: port_binds = [(default_ip, port) for port in parse_port_range(parts[0], self.client)] elif p_len == 3: # We only allow IPv4 and IPv6 addresses for the bind address ipaddr = parts[0] if not re.match(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$', parts[0]) and not re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr): self.fail(('Bind addresses for published ports must be IPv4 or IPv6 addresses, not hostnames. ' 'Use the dig lookup to resolve hostnames. (Found hostname: {0})').format(ipaddr)) if re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr): ipaddr = ipaddr[1:-1] if parts[1]: port_binds = [(ipaddr, port) for port in parse_port_range(parts[1], self.client)] else: port_binds = len(container_ports) * [(ipaddr,)] for bind, container_port in zip(port_binds, container_ports): idx = '{0}/{1}'.format(container_port, protocol) if protocol else container_port if idx in binds: old_bind = binds[idx] if isinstance(old_bind, list): old_bind.append(bind) else: binds[idx] = [old_bind, bind] else: binds[idx] = bind return binds def _get_volume_binds(self, volumes): ''' Extract host bindings, if any, from list of volume mapping strings. :return: dictionary of bind mappings ''' result = dict() if volumes: for vol in volumes: host = None if ':' in vol: parts = vol.split(':') if len(parts) == 3: host, container, mode = parts if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) elif len(parts) == 2: if not is_volume_permissions(parts[1]): host, container, mode = (vol.split(':') + ['rw']) if host is not None: result[host] = dict( bind=container, mode=mode ) return result def _parse_exposed_ports(self, published_ports): ''' Parse exposed ports from docker CLI-style ports syntax. ''' exposed = [] if self.exposed_ports: for port in self.exposed_ports: port = str(port).strip() protocol = 'tcp' match = re.search(r'(/.+$)', port) if match: protocol = match.group(1).replace('/', '') port = re.sub(r'/.+$', '', port) exposed.append((port, protocol)) if published_ports: # Any published port should also be exposed for publish_port in published_ports: match = False if isinstance(publish_port, string_types) and '/' in publish_port: port, protocol = publish_port.split('/') port = int(port) else: protocol = 'tcp' port = int(publish_port) for exposed_port in exposed: if exposed_port[1] != protocol: continue if isinstance(exposed_port[0], string_types) and '-' in exposed_port[0]: start_port, end_port = exposed_port[0].split('-') if int(start_port) <= port <= int(end_port): match = True elif exposed_port[0] == port: match = True if not match: exposed.append((port, protocol)) return exposed @staticmethod def _parse_links(links): ''' Turn links into a dictionary ''' if links is None: return None result = [] for link in links: parsed_link = link.split(':', 1) if len(parsed_link) == 2: result.append((parsed_link[0], parsed_link[1])) else: result.append((parsed_link[0], parsed_link[0])) return result def _parse_ulimits(self): ''' Turn ulimits into an array of Ulimit objects ''' if self.ulimits is None: return None results = [] for limit in self.ulimits: limits = dict() pieces = limit.split(':') if len(pieces) >= 2: limits['name'] = pieces[0] limits['soft'] = int(pieces[1]) limits['hard'] = int(pieces[1]) if len(pieces) == 3: limits['hard'] = int(pieces[2]) try: results.append(Ulimit(**limits)) except ValueError as exc: self.fail("Error parsing ulimits value %s - %s" % (limit, exc)) return results def _parse_sysctls(self): ''' Turn sysctls into an hash of Sysctl objects ''' return self.sysctls def _parse_log_config(self): ''' Create a LogConfig object ''' if self.log_driver is None: return None options = dict( Type=self.log_driver, Config=dict() ) if self.log_options is not None: options['Config'] = dict() for k, v in self.log_options.items(): if not isinstance(v, string_types): self.client.module.warn( "Non-string value found for log_options option '%s'. The value is automatically converted to '%s'. " "If this is not correct, or you want to avoid such warnings, please quote the value." % (k, str(v)) ) v = str(v) self.log_options[k] = v options['Config'][k] = v try: return LogConfig(**options) except ValueError as exc: self.fail('Error parsing logging options - %s' % (exc)) def _parse_tmpfs(self): ''' Turn tmpfs into a hash of Tmpfs objects ''' result = dict() if self.tmpfs is None: return result for tmpfs_spec in self.tmpfs: split_spec = tmpfs_spec.split(":", 1) if len(split_spec) > 1: result[split_spec[0]] = split_spec[1] else: result[split_spec[0]] = "" return result def _get_environment(self): """ If environment file is combined with explicit environment variables, the explicit environment variables take precedence. """ final_env = {} if self.env_file: parsed_env_file = utils.parse_env_file(self.env_file) for name, value in parsed_env_file.items(): final_env[name] = str(value) if self.env: for name, value in self.env.items(): if not isinstance(value, string_types): self.fail("Non-string value found for env option. Ambiguous env options must be " "wrapped in quotes to avoid them being interpreted. Key: %s" % (name, )) final_env[name] = str(value) return final_env def _get_network_id(self, network_name): network_id = None try: for network in self.client.networks(names=[network_name]): if network['Name'] == network_name: network_id = network['Id'] break except Exception as exc: self.fail("Error getting network id for %s - %s" % (network_name, str(exc))) return network_id def _process_mounts(self): if self.mounts is None: return None, None mounts_list = [] mounts_expected = [] for mount in self.mounts: target = mount['target'] datatype = mount['type'] mount_dict = dict(mount) # Sanity checks (so we don't wait for docker-py to barf on input) if mount_dict.get('source') is None and datatype != 'tmpfs': self.client.fail('source must be specified for mount "{0}" of type "{1}"'.format(target, datatype)) mount_option_types = dict( volume_driver='volume', volume_options='volume', propagation='bind', no_copy='volume', labels='volume', tmpfs_size='tmpfs', tmpfs_mode='tmpfs', ) for option, req_datatype in mount_option_types.items(): if mount_dict.get(option) is not None and datatype != req_datatype: self.client.fail('{0} cannot be specified for mount "{1}" of type "{2}" (needs type "{3}")'.format(option, target, datatype, req_datatype)) # Handle volume_driver and volume_options volume_driver = mount_dict.pop('volume_driver') volume_options = mount_dict.pop('volume_options') if volume_driver: if volume_options: volume_options = clean_dict_booleans_for_docker_api(volume_options) mount_dict['driver_config'] = docker_types.DriverConfig(name=volume_driver, options=volume_options) if mount_dict['labels']: mount_dict['labels'] = clean_dict_booleans_for_docker_api(mount_dict['labels']) if mount_dict.get('tmpfs_size') is not None: try: mount_dict['tmpfs_size'] = human_to_bytes(mount_dict['tmpfs_size']) except ValueError as exc: self.fail('Failed to convert tmpfs_size of mount "{0}" to bytes: {1}'.format(target, exc)) if mount_dict.get('tmpfs_mode') is not None: try: mount_dict['tmpfs_mode'] = int(mount_dict['tmpfs_mode'], 8) except Exception as dummy: self.client.fail('tmp_fs mode of mount "{0}" is not an octal string!'.format(target)) # Fill expected mount dict mount_expected = dict(mount) mount_expected['tmpfs_size'] = mount_dict['tmpfs_size'] mount_expected['tmpfs_mode'] = mount_dict['tmpfs_mode'] # Add result to lists mounts_list.append(docker_types.Mount(**mount_dict)) mounts_expected.append(omit_none_from_dict(mount_expected)) return mounts_list, mounts_expected def _process_rate_bps(self, option): """ Format device_read_bps and device_write_bps option """ devices_list = [] for v in getattr(self, option): device_dict = dict((x.title(), y) for x, y in v.items()) device_dict['Rate'] = human_to_bytes(device_dict['Rate']) devices_list.append(device_dict) setattr(self, option, devices_list) def _process_rate_iops(self, option): """ Format device_read_iops and device_write_iops option """ devices_list = [] for v in getattr(self, option): device_dict = dict((x.title(), y) for x, y in v.items()) devices_list.append(device_dict) setattr(self, option, devices_list) def _replace_container_names(self, mode): """ Parse IPC and PID modes. If they contain a container name, replace with the container's ID. """ if mode is None or not mode.startswith('container:'): return mode container_name = mode[len('container:'):] # Try to inspect container to see whether this is an ID or a # name (and in the latter case, retrieve it's ID) container = self.client.get_container(container_name) if container is None: # If we can't find the container, issue a warning and continue with # what the user specified. self.client.module.warn('Cannot find a container with name or ID "{0}"'.format(container_name)) return mode return 'container:{0}'.format(container['Id']) def _check_mount_target_collisions(self): last = dict() def f(t, name): if t in last: if name == last[t]: self.client.fail('The mount point "{0}" appears twice in the {1} option'.format(t, name)) else: self.client.fail('The mount point "{0}" appears both in the {1} and {2} option'.format(t, name, last[t])) last[t] = name if self.expected_mounts: for t in [m['target'] for m in self.expected_mounts]: f(t, 'mounts') if self.volumes: for v in self.volumes: vs = v.split(':') f(vs[0 if len(vs) == 1 else 1], 'volumes') class Container(DockerBaseClass): def __init__(self, container, parameters): super(Container, self).__init__() self.raw = container self.Id = None self.container = container if container: self.Id = container['Id'] self.Image = container['Image'] self.log(self.container, pretty_print=True) self.parameters = parameters self.parameters.expected_links = None self.parameters.expected_ports = None self.parameters.expected_exposed = None self.parameters.expected_volumes = None self.parameters.expected_ulimits = None self.parameters.expected_sysctls = None self.parameters.expected_etc_hosts = None self.parameters.expected_env = None self.parameters_map = dict() self.parameters_map['expected_links'] = 'links' self.parameters_map['expected_ports'] = 'expected_ports' self.parameters_map['expected_exposed'] = 'exposed_ports' self.parameters_map['expected_volumes'] = 'volumes' self.parameters_map['expected_ulimits'] = 'ulimits' self.parameters_map['expected_sysctls'] = 'sysctls' self.parameters_map['expected_etc_hosts'] = 'etc_hosts' self.parameters_map['expected_env'] = 'env' self.parameters_map['expected_entrypoint'] = 'entrypoint' self.parameters_map['expected_binds'] = 'volumes' self.parameters_map['expected_cmd'] = 'command' self.parameters_map['expected_devices'] = 'devices' self.parameters_map['expected_healthcheck'] = 'healthcheck' self.parameters_map['expected_mounts'] = 'mounts' def fail(self, msg): self.parameters.client.fail(msg) @property def exists(self): return True if self.container else False @property def running(self): if self.container and self.container.get('State'): if self.container['State'].get('Running') and not self.container['State'].get('Ghost', False): return True return False @property def paused(self): if self.container and self.container.get('State'): return self.container['State'].get('Paused', False) return False def _compare(self, a, b, compare): ''' Compare values a and b as described in compare. ''' return compare_generic(a, b, compare['comparison'], compare['type']) def _decode_mounts(self, mounts): if not mounts: return mounts result = [] empty_dict = dict() for mount in mounts: res = dict() res['type'] = mount.get('Type') res['source'] = mount.get('Source') res['target'] = mount.get('Target') res['read_only'] = mount.get('ReadOnly', False) # golang's omitempty for bool returns None for False res['consistency'] = mount.get('Consistency') res['propagation'] = mount.get('BindOptions', empty_dict).get('Propagation') res['no_copy'] = mount.get('VolumeOptions', empty_dict).get('NoCopy', False) res['labels'] = mount.get('VolumeOptions', empty_dict).get('Labels', empty_dict) res['volume_driver'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Name') res['volume_options'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Options', empty_dict) res['tmpfs_size'] = mount.get('TmpfsOptions', empty_dict).get('SizeBytes') res['tmpfs_mode'] = mount.get('TmpfsOptions', empty_dict).get('Mode') result.append(res) return result def has_different_configuration(self, image): ''' Diff parameters vs existing container config. Returns tuple: (True | False, List of differences) ''' self.log('Starting has_different_configuration') self.parameters.expected_entrypoint = self._get_expected_entrypoint() self.parameters.expected_links = self._get_expected_links() self.parameters.expected_ports = self._get_expected_ports() self.parameters.expected_exposed = self._get_expected_exposed(image) self.parameters.expected_volumes = self._get_expected_volumes(image) self.parameters.expected_binds = self._get_expected_binds(image) self.parameters.expected_ulimits = self._get_expected_ulimits(self.parameters.ulimits) self.parameters.expected_sysctls = self._get_expected_sysctls(self.parameters.sysctls) self.parameters.expected_etc_hosts = self._convert_simple_dict_to_list('etc_hosts') self.parameters.expected_env = self._get_expected_env(image) self.parameters.expected_cmd = self._get_expected_cmd() self.parameters.expected_devices = self._get_expected_devices() self.parameters.expected_healthcheck = self._get_expected_healthcheck() if not self.container.get('HostConfig'): self.fail("has_config_diff: Error parsing container properties. HostConfig missing.") if not self.container.get('Config'): self.fail("has_config_diff: Error parsing container properties. Config missing.") if not self.container.get('NetworkSettings'): self.fail("has_config_diff: Error parsing container properties. NetworkSettings missing.") host_config = self.container['HostConfig'] log_config = host_config.get('LogConfig', dict()) restart_policy = host_config.get('RestartPolicy', dict()) config = self.container['Config'] network = self.container['NetworkSettings'] # The previous version of the docker module ignored the detach state by # assuming if the container was running, it must have been detached. detach = not (config.get('AttachStderr') and config.get('AttachStdout')) # "ExposedPorts": null returns None type & causes AttributeError - PR #5517 if config.get('ExposedPorts') is not None: expected_exposed = [self._normalize_port(p) for p in config.get('ExposedPorts', dict()).keys()] else: expected_exposed = [] # Map parameters to container inspect results config_mapping = dict( expected_cmd=config.get('Cmd'), domainname=config.get('Domainname'), hostname=config.get('Hostname'), user=config.get('User'), detach=detach, init=host_config.get('Init'), interactive=config.get('OpenStdin'), capabilities=host_config.get('CapAdd'), cap_drop=host_config.get('CapDrop'), expected_devices=host_config.get('Devices'), dns_servers=host_config.get('Dns'), dns_opts=host_config.get('DnsOptions'), dns_search_domains=host_config.get('DnsSearch'), expected_env=(config.get('Env') or []), expected_entrypoint=config.get('Entrypoint'), expected_etc_hosts=host_config['ExtraHosts'], expected_exposed=expected_exposed, groups=host_config.get('GroupAdd'), ipc_mode=host_config.get("IpcMode"), labels=config.get('Labels'), expected_links=host_config.get('Links'), mac_address=network.get('MacAddress'), memory_swappiness=host_config.get('MemorySwappiness'), network_mode=host_config.get('NetworkMode'), userns_mode=host_config.get('UsernsMode'), oom_killer=host_config.get('OomKillDisable'), oom_score_adj=host_config.get('OomScoreAdj'), pid_mode=host_config.get('PidMode'), privileged=host_config.get('Privileged'), expected_ports=host_config.get('PortBindings'), read_only=host_config.get('ReadonlyRootfs'), restart_policy=restart_policy.get('Name'), runtime=host_config.get('Runtime'), shm_size=host_config.get('ShmSize'), security_opts=host_config.get("SecurityOpt"), stop_signal=config.get("StopSignal"), tmpfs=host_config.get('Tmpfs'), tty=config.get('Tty'), expected_ulimits=host_config.get('Ulimits'), expected_sysctls=host_config.get('Sysctls'), uts=host_config.get('UTSMode'), expected_volumes=config.get('Volumes'), expected_binds=host_config.get('Binds'), volume_driver=host_config.get('VolumeDriver'), volumes_from=host_config.get('VolumesFrom'), working_dir=config.get('WorkingDir'), publish_all_ports=host_config.get('PublishAllPorts'), expected_healthcheck=config.get('Healthcheck'), disable_healthcheck=(not config.get('Healthcheck') or config.get('Healthcheck').get('Test') == ['NONE']), device_read_bps=host_config.get('BlkioDeviceReadBps'), device_write_bps=host_config.get('BlkioDeviceWriteBps'), device_read_iops=host_config.get('BlkioDeviceReadIOps'), device_write_iops=host_config.get('BlkioDeviceWriteIOps'), pids_limit=host_config.get('PidsLimit'), # According to https://github.com/moby/moby/, support for HostConfig.Mounts # has been included at least since v17.03.0-ce, which has API version 1.26. # The previous tag, v1.9.1, has API version 1.21 and does not have # HostConfig.Mounts. I have no idea what about API 1.25... expected_mounts=self._decode_mounts(host_config.get('Mounts')), ) # Options which don't make sense without their accompanying option if self.parameters.restart_policy: config_mapping['restart_retries'] = restart_policy.get('MaximumRetryCount') if self.parameters.log_driver: config_mapping['log_driver'] = log_config.get('Type') config_mapping['log_options'] = log_config.get('Config') if self.parameters.client.option_minimal_versions['auto_remove']['supported']: # auto_remove is only supported in Docker SDK for Python >= 2.0.0; unfortunately # it has a default value, that's why we have to jump through the hoops here config_mapping['auto_remove'] = host_config.get('AutoRemove') if self.parameters.client.option_minimal_versions['stop_timeout']['supported']: # stop_timeout is only supported in Docker SDK for Python >= 2.1. Note that # stop_timeout has a hybrid role, in that it used to be something only used # for stopping containers, and is now also used as a container property. # That's why it needs special handling here. config_mapping['stop_timeout'] = config.get('StopTimeout') if self.parameters.client.docker_api_version < LooseVersion('1.22'): # For docker API < 1.22, update_container() is not supported. Thus # we need to handle all limits which are usually handled by # update_container() as configuration changes which require a container # restart. config_mapping.update(dict( blkio_weight=host_config.get('BlkioWeight'), cpu_period=host_config.get('CpuPeriod'), cpu_quota=host_config.get('CpuQuota'), cpu_shares=host_config.get('CpuShares'), cpuset_cpus=host_config.get('CpusetCpus'), cpuset_mems=host_config.get('CpusetMems'), kernel_memory=host_config.get("KernelMemory"), memory=host_config.get('Memory'), memory_reservation=host_config.get('MemoryReservation'), memory_swap=host_config.get('MemorySwap'), )) differences = DifferenceTracker() for key, value in config_mapping.items(): minimal_version = self.parameters.client.option_minimal_versions.get(key, {}) if not minimal_version.get('supported', True): continue compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)] self.log('check differences %s %s vs %s (%s)' % (key, getattr(self.parameters, key), str(value), compare)) if getattr(self.parameters, key, None) is not None: match = self._compare(getattr(self.parameters, key), value, compare) if not match: # no match. record the differences p = getattr(self.parameters, key) c = value if compare['type'] == 'set': # Since the order does not matter, sort so that the diff output is better. if p is not None: p = sorted(p) if c is not None: c = sorted(c) elif compare['type'] == 'set(dict)': # Since the order does not matter, sort so that the diff output is better. if key == 'expected_mounts': # For selected values, use one entry as key def sort_key_fn(x): return x['target'] else: # We sort the list of dictionaries by using the sorted items of a dict as its key. def sort_key_fn(x): return sorted((a, str(b)) for a, b in x.items()) if p is not None: p = sorted(p, key=sort_key_fn) if c is not None: c = sorted(c, key=sort_key_fn) differences.add(key, parameter=p, active=c) has_differences = not differences.empty return has_differences, differences def has_different_resource_limits(self): ''' Diff parameters and container resource limits ''' if not self.container.get('HostConfig'): self.fail("limits_differ_from_container: Error parsing container properties. HostConfig missing.") if self.parameters.client.docker_api_version < LooseVersion('1.22'): # update_container() call not supported return False, [] host_config = self.container['HostConfig'] config_mapping = dict( blkio_weight=host_config.get('BlkioWeight'), cpu_period=host_config.get('CpuPeriod'), cpu_quota=host_config.get('CpuQuota'), cpu_shares=host_config.get('CpuShares'), cpuset_cpus=host_config.get('CpusetCpus'), cpuset_mems=host_config.get('CpusetMems'), kernel_memory=host_config.get("KernelMemory"), memory=host_config.get('Memory'), memory_reservation=host_config.get('MemoryReservation'), memory_swap=host_config.get('MemorySwap'), ) differences = DifferenceTracker() for key, value in config_mapping.items(): if getattr(self.parameters, key, None): compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)] match = self._compare(getattr(self.parameters, key), value, compare) if not match: # no match. record the differences differences.add(key, parameter=getattr(self.parameters, key), active=value) different = not differences.empty return different, differences def has_network_differences(self): ''' Check if the container is connected to requested networks with expected options: links, aliases, ipv4, ipv6 ''' different = False differences = [] if not self.parameters.networks: return different, differences if not self.container.get('NetworkSettings'): self.fail("has_missing_networks: Error parsing container properties. NetworkSettings missing.") connected_networks = self.container['NetworkSettings']['Networks'] for network in self.parameters.networks: network_info = connected_networks.get(network['name']) if network_info is None: different = True differences.append(dict( parameter=network, container=None )) else: diff = False network_info_ipam = network_info.get('IPAMConfig', {}) if network.get('ipv4_address') and network['ipv4_address'] != network_info_ipam.get('IPv4Address'): diff = True if network.get('ipv6_address') and network['ipv6_address'] != network_info_ipam.get('IPv6Address'): diff = True if network.get('aliases'): if not compare_generic(network['aliases'], network_info.get('Aliases'), 'allow_more_present', 'set'): diff = True if network.get('links'): expected_links = [] for link, alias in network['links']: expected_links.append("%s:%s" % (link, alias)) if not compare_generic(expected_links, network_info.get('Links'), 'allow_more_present', 'set'): diff = True if diff: different = True differences.append(dict( parameter=network, container=dict( name=network['name'], ipv4_address=network_info_ipam.get('IPv4Address'), ipv6_address=network_info_ipam.get('IPv6Address'), aliases=network_info.get('Aliases'), links=network_info.get('Links') ) )) return different, differences def has_extra_networks(self): ''' Check if the container is connected to non-requested networks ''' extra_networks = [] extra = False if not self.container.get('NetworkSettings'): self.fail("has_extra_networks: Error parsing container properties. NetworkSettings missing.") connected_networks = self.container['NetworkSettings'].get('Networks') if connected_networks: for network, network_config in connected_networks.items(): keep = False if self.parameters.networks: for expected_network in self.parameters.networks: if expected_network['name'] == network: keep = True if not keep: extra = True extra_networks.append(dict(name=network, id=network_config['NetworkID'])) return extra, extra_networks def _get_expected_devices(self): if not self.parameters.devices: return None expected_devices = [] for device in self.parameters.devices: parts = device.split(':') if len(parts) == 1: expected_devices.append( dict( CgroupPermissions='rwm', PathInContainer=parts[0], PathOnHost=parts[0] )) elif len(parts) == 2: parts = device.split(':') expected_devices.append( dict( CgroupPermissions='rwm', PathInContainer=parts[1], PathOnHost=parts[0] ) ) else: expected_devices.append( dict( CgroupPermissions=parts[2], PathInContainer=parts[1], PathOnHost=parts[0] )) return expected_devices def _get_expected_entrypoint(self): if not self.parameters.entrypoint: return None return shlex.split(self.parameters.entrypoint) def _get_expected_ports(self): if not self.parameters.published_ports: return None expected_bound_ports = {} for container_port, config in self.parameters.published_ports.items(): if isinstance(container_port, int): container_port = "%s/tcp" % container_port if len(config) == 1: if isinstance(config[0], int): expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': config[0]}] else: expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': ""}] elif isinstance(config[0], tuple): expected_bound_ports[container_port] = [] for host_ip, host_port in config: expected_bound_ports[container_port].append({'HostIp': host_ip, 'HostPort': str(host_port)}) else: expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': str(config[1])}] return expected_bound_ports def _get_expected_links(self): if self.parameters.links is None: return None self.log('parameter links:') self.log(self.parameters.links, pretty_print=True) exp_links = [] for link, alias in self.parameters.links: exp_links.append("/%s:%s/%s" % (link, ('/' + self.parameters.name), alias)) return exp_links def _get_expected_binds(self, image): self.log('_get_expected_binds') image_vols = [] if image: image_vols = self._get_image_binds(image[self.parameters.client.image_inspect_source].get('Volumes')) param_vols = [] if self.parameters.volumes: for vol in self.parameters.volumes: host = None if ':' in vol: if len(vol.split(':')) == 3: host, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): host, container, mode = vol.split(':') + ['rw'] if host: param_vols.append("%s:%s:%s" % (host, container, mode)) result = list(set(image_vols + param_vols)) self.log("expected_binds:") self.log(result, pretty_print=True) return result def _get_image_binds(self, volumes): ''' Convert array of binds to array of strings with format host_path:container_path:mode :param volumes: array of bind dicts :return: array of strings ''' results = [] if isinstance(volumes, dict): results += self._get_bind_from_dict(volumes) elif isinstance(volumes, list): for vol in volumes: results += self._get_bind_from_dict(vol) return results @staticmethod def _get_bind_from_dict(volume_dict): results = [] if volume_dict: for host_path, config in volume_dict.items(): if isinstance(config, dict) and config.get('bind'): container_path = config.get('bind') mode = config.get('mode', 'rw') results.append("%s:%s:%s" % (host_path, container_path, mode)) return results def _get_expected_volumes(self, image): self.log('_get_expected_volumes') expected_vols = dict() if image and image[self.parameters.client.image_inspect_source].get('Volumes'): expected_vols.update(image[self.parameters.client.image_inspect_source].get('Volumes')) if self.parameters.volumes: for vol in self.parameters.volumes: container = None if ':' in vol: if len(vol.split(':')) == 3: dummy, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): dummy, container, mode = vol.split(':') + ['rw'] new_vol = dict() if container: new_vol[container] = dict() else: new_vol[vol] = dict() expected_vols.update(new_vol) if not expected_vols: expected_vols = None self.log("expected_volumes:") self.log(expected_vols, pretty_print=True) return expected_vols def _get_expected_env(self, image): self.log('_get_expected_env') expected_env = dict() if image and image[self.parameters.client.image_inspect_source].get('Env'): for env_var in image[self.parameters.client.image_inspect_source]['Env']: parts = env_var.split('=', 1) expected_env[parts[0]] = parts[1] if self.parameters.env: expected_env.update(self.parameters.env) param_env = [] for key, value in expected_env.items(): param_env.append("%s=%s" % (key, value)) return param_env def _get_expected_exposed(self, image): self.log('_get_expected_exposed') image_ports = [] if image: image_exposed_ports = image[self.parameters.client.image_inspect_source].get('ExposedPorts') or {} image_ports = [self._normalize_port(p) for p in image_exposed_ports.keys()] param_ports = [] if self.parameters.ports: param_ports = [str(p[0]) + '/' + p[1] for p in self.parameters.ports] result = list(set(image_ports + param_ports)) self.log(result, pretty_print=True) return result def _get_expected_ulimits(self, config_ulimits): self.log('_get_expected_ulimits') if config_ulimits is None: return None results = [] for limit in config_ulimits: results.append(dict( Name=limit.name, Soft=limit.soft, Hard=limit.hard )) return results def _get_expected_sysctls(self, config_sysctls): self.log('_get_expected_sysctls') if config_sysctls is None: return None result = dict() for key, value in config_sysctls.items(): result[key] = str(value) return result def _get_expected_cmd(self): self.log('_get_expected_cmd') if not self.parameters.command: return None return shlex.split(self.parameters.command) def _convert_simple_dict_to_list(self, param_name, join_with=':'): if getattr(self.parameters, param_name, None) is None: return None results = [] for key, value in getattr(self.parameters, param_name).items(): results.append("%s%s%s" % (key, join_with, value)) return results def _normalize_port(self, port): if '/' not in port: return port + '/tcp' return port def _get_expected_healthcheck(self): self.log('_get_expected_healthcheck') expected_healthcheck = dict() if self.parameters.healthcheck: expected_healthcheck.update([(k.title().replace("_", ""), v) for k, v in self.parameters.healthcheck.items()]) return expected_healthcheck class ContainerManager(DockerBaseClass): ''' Perform container management tasks ''' def __init__(self, client): super(ContainerManager, self).__init__() if client.module.params.get('log_options') and not client.module.params.get('log_driver'): client.module.warn('log_options is ignored when log_driver is not specified') if client.module.params.get('healthcheck') and not client.module.params.get('healthcheck').get('test'): client.module.warn('healthcheck is ignored when test is not specified') if client.module.params.get('restart_retries') is not None and not client.module.params.get('restart_policy'): client.module.warn('restart_retries is ignored when restart_policy is not specified') self.client = client self.parameters = TaskParameters(client) self.check_mode = self.client.check_mode self.results = {'changed': False, 'actions': []} self.diff = {} self.diff_tracker = DifferenceTracker() self.facts = {} state = self.parameters.state if state in ('stopped', 'started', 'present'): self.present(state) elif state == 'absent': self.absent() if not self.check_mode and not self.parameters.debug: self.results.pop('actions') if self.client.module._diff or self.parameters.debug: self.diff['before'], self.diff['after'] = self.diff_tracker.get_before_after() self.results['diff'] = self.diff if self.facts: self.results['ansible_facts'] = {'docker_container': self.facts} self.results['container'] = self.facts def present(self, state): container = self._get_container(self.parameters.name) was_running = container.running was_paused = container.paused container_created = False # If the image parameter was passed then we need to deal with the image # version comparison. Otherwise we handle this depending on whether # the container already runs or not; in the former case, in case the # container needs to be restarted, we use the existing container's # image ID. image = self._get_image() self.log(image, pretty_print=True) if not container.exists: # New container self.log('No container found') if not self.parameters.image: self.fail('Cannot create container when image is not specified!') self.diff_tracker.add('exists', parameter=True, active=False) new_container = self.container_create(self.parameters.image, self.parameters.create_parameters) if new_container: container = new_container container_created = True else: # Existing container different, differences = container.has_different_configuration(image) image_different = False if self.parameters.comparisons['image']['comparison'] == 'strict': image_different = self._image_is_different(image, container) if image_different or different or self.parameters.recreate: self.diff_tracker.merge(differences) self.diff['differences'] = differences.get_legacy_docker_container_diffs() if image_different: self.diff['image_different'] = True self.log("differences") self.log(differences.get_legacy_docker_container_diffs(), pretty_print=True) image_to_use = self.parameters.image if not image_to_use and container and container.Image: image_to_use = container.Image if not image_to_use: self.fail('Cannot recreate container when image is not specified or cannot be extracted from current container!') if container.running: self.container_stop(container.Id) self.container_remove(container.Id) new_container = self.container_create(image_to_use, self.parameters.create_parameters) if new_container: container = new_container container_created = True if container and container.exists: container = self.update_limits(container) container = self.update_networks(container, container_created) if state == 'started' and not container.running: self.diff_tracker.add('running', parameter=True, active=was_running) container = self.container_start(container.Id) elif state == 'started' and self.parameters.restart: self.diff_tracker.add('running', parameter=True, active=was_running) self.diff_tracker.add('restarted', parameter=True, active=False) container = self.container_restart(container.Id) elif state == 'stopped' and container.running: self.diff_tracker.add('running', parameter=False, active=was_running) self.container_stop(container.Id) container = self._get_container(container.Id) if state == 'started' and container.paused != self.parameters.paused: self.diff_tracker.add('paused', parameter=self.parameters.paused, active=was_paused) if not self.check_mode: try: if self.parameters.paused: self.client.pause(container=container.Id) else: self.client.unpause(container=container.Id) except Exception as exc: self.fail("Error %s container %s: %s" % ( "pausing" if self.parameters.paused else "unpausing", container.Id, str(exc) )) container = self._get_container(container.Id) self.results['changed'] = True self.results['actions'].append(dict(set_paused=self.parameters.paused)) self.facts = container.raw def absent(self): container = self._get_container(self.parameters.name) if container.exists: if container.running: self.diff_tracker.add('running', parameter=False, active=True) self.container_stop(container.Id) self.diff_tracker.add('exists', parameter=False, active=True) self.container_remove(container.Id) def fail(self, msg, **kwargs): self.client.fail(msg, **kwargs) def _output_logs(self, msg): self.client.module.log(msg=msg) def _get_container(self, container): ''' Expects container ID or Name. Returns a container object ''' return Container(self.client.get_container(container), self.parameters) def _get_image(self): if not self.parameters.image: self.log('No image specified') return None if is_image_name_id(self.parameters.image): image = self.client.find_image_by_id(self.parameters.image) else: repository, tag = utils.parse_repository_tag(self.parameters.image) if not tag: tag = "latest" image = self.client.find_image(repository, tag) if not image or self.parameters.pull: if not self.check_mode: self.log("Pull the image.") image, alreadyToLatest = self.client.pull_image(repository, tag) if alreadyToLatest: self.results['changed'] = False else: self.results['changed'] = True self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag))) elif not image: # If the image isn't there, claim we'll pull. # (Implicitly: if the image is there, claim it already was latest.) self.results['changed'] = True self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag))) self.log("image") self.log(image, pretty_print=True) return image def _image_is_different(self, image, container): if image and image.get('Id'): if container and container.Image: if image.get('Id') != container.Image: self.diff_tracker.add('image', parameter=image.get('Id'), active=container.Image) return True return False def update_limits(self, container): limits_differ, different_limits = container.has_different_resource_limits() if limits_differ: self.log("limit differences:") self.log(different_limits.get_legacy_docker_container_diffs(), pretty_print=True) self.diff_tracker.merge(different_limits) if limits_differ and not self.check_mode: self.container_update(container.Id, self.parameters.update_parameters) return self._get_container(container.Id) return container def update_networks(self, container, container_created): updated_container = container if self.parameters.comparisons['networks']['comparison'] != 'ignore' or container_created: has_network_differences, network_differences = container.has_network_differences() if has_network_differences: if self.diff.get('differences'): self.diff['differences'].append(dict(network_differences=network_differences)) else: self.diff['differences'] = [dict(network_differences=network_differences)] for netdiff in network_differences: self.diff_tracker.add( 'network.{0}'.format(netdiff['parameter']['name']), parameter=netdiff['parameter'], active=netdiff['container'] ) self.results['changed'] = True updated_container = self._add_networks(container, network_differences) if (self.parameters.comparisons['networks']['comparison'] == 'strict' and self.parameters.networks is not None) or self.parameters.purge_networks: has_extra_networks, extra_networks = container.has_extra_networks() if has_extra_networks: if self.diff.get('differences'): self.diff['differences'].append(dict(purge_networks=extra_networks)) else: self.diff['differences'] = [dict(purge_networks=extra_networks)] for extra_network in extra_networks: self.diff_tracker.add( 'network.{0}'.format(extra_network['name']), active=extra_network ) self.results['changed'] = True updated_container = self._purge_networks(container, extra_networks) return updated_container def _add_networks(self, container, differences): for diff in differences: # remove the container from the network, if connected if diff.get('container'): self.results['actions'].append(dict(removed_from_network=diff['parameter']['name'])) if not self.check_mode: try: self.client.disconnect_container_from_network(container.Id, diff['parameter']['id']) except Exception as exc: self.fail("Error disconnecting container from network %s - %s" % (diff['parameter']['name'], str(exc))) # connect to the network params = dict() for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'): if diff['parameter'].get(para): params[para] = diff['parameter'][para] self.results['actions'].append(dict(added_to_network=diff['parameter']['name'], network_parameters=params)) if not self.check_mode: try: self.log("Connecting container to network %s" % diff['parameter']['id']) self.log(params, pretty_print=True) self.client.connect_container_to_network(container.Id, diff['parameter']['id'], **params) except Exception as exc: self.fail("Error connecting container to network %s - %s" % (diff['parameter']['name'], str(exc))) return self._get_container(container.Id) def _purge_networks(self, container, networks): for network in networks: self.results['actions'].append(dict(removed_from_network=network['name'])) if not self.check_mode: try: self.client.disconnect_container_from_network(container.Id, network['name']) except Exception as exc: self.fail("Error disconnecting container from network %s - %s" % (network['name'], str(exc))) return self._get_container(container.Id) def container_create(self, image, create_parameters): self.log("create container") self.log("image: %s parameters:" % image) self.log(create_parameters, pretty_print=True) self.results['actions'].append(dict(created="Created container", create_parameters=create_parameters)) self.results['changed'] = True new_container = None if not self.check_mode: try: new_container = self.client.create_container(image, **create_parameters) self.client.report_warnings(new_container) except Exception as exc: self.fail("Error creating container: %s" % str(exc)) return self._get_container(new_container['Id']) return new_container def container_start(self, container_id): self.log("start container %s" % (container_id)) self.results['actions'].append(dict(started=container_id)) self.results['changed'] = True if not self.check_mode: try: self.client.start(container=container_id) except Exception as exc: self.fail("Error starting container %s: %s" % (container_id, str(exc))) if not self.parameters.detach: if self.client.docker_py_version >= LooseVersion('3.0'): status = self.client.wait(container_id)['StatusCode'] else: status = self.client.wait(container_id) if self.parameters.auto_remove: output = "Cannot retrieve result as auto_remove is enabled" if self.parameters.output_logs: self.client.module.warn('Cannot output_logs if auto_remove is enabled!') else: config = self.client.inspect_container(container_id) logging_driver = config['HostConfig']['LogConfig']['Type'] if logging_driver in ('json-file', 'journald'): output = self.client.logs(container_id, stdout=True, stderr=True, stream=False, timestamps=False) if self.parameters.output_logs: self._output_logs(msg=output) else: output = "Result logged using `%s` driver" % logging_driver if status != 0: self.fail(output, status=status) if self.parameters.cleanup: self.container_remove(container_id, force=True) insp = self._get_container(container_id) if insp.raw: insp.raw['Output'] = output else: insp.raw = dict(Output=output) return insp return self._get_container(container_id) def container_remove(self, container_id, link=False, force=False): volume_state = (not self.parameters.keep_volumes) self.log("remove container container:%s v:%s link:%s force%s" % (container_id, volume_state, link, force)) self.results['actions'].append(dict(removed=container_id, volume_state=volume_state, link=link, force=force)) self.results['changed'] = True response = None if not self.check_mode: count = 0 while True: try: response = self.client.remove_container(container_id, v=volume_state, link=link, force=force) except NotFound as dummy: pass except APIError as exc: if 'Unpause the container before stopping or killing' in exc.explanation: # New docker daemon versions do not allow containers to be removed # if they are paused. Make sure we don't end up in an infinite loop. if count == 3: self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc))) count += 1 # Unpause try: self.client.unpause(container=container_id) except Exception as exc2: self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2))) # Now try again continue if 'removal of container ' in exc.explanation and ' is already in progress' in exc.explanation: pass else: self.fail("Error removing container %s: %s" % (container_id, str(exc))) except Exception as exc: self.fail("Error removing container %s: %s" % (container_id, str(exc))) # We only loop when explicitly requested by 'continue' break return response def container_update(self, container_id, update_parameters): if update_parameters: self.log("update container %s" % (container_id)) self.log(update_parameters, pretty_print=True) self.results['actions'].append(dict(updated=container_id, update_parameters=update_parameters)) self.results['changed'] = True if not self.check_mode and callable(getattr(self.client, 'update_container')): try: result = self.client.update_container(container_id, **update_parameters) self.client.report_warnings(result) except Exception as exc: self.fail("Error updating container %s: %s" % (container_id, str(exc))) return self._get_container(container_id) def container_kill(self, container_id): self.results['actions'].append(dict(killed=container_id, signal=self.parameters.kill_signal)) self.results['changed'] = True response = None if not self.check_mode: try: if self.parameters.kill_signal: response = self.client.kill(container_id, signal=self.parameters.kill_signal) else: response = self.client.kill(container_id) except Exception as exc: self.fail("Error killing container %s: %s" % (container_id, exc)) return response def container_restart(self, container_id): self.results['actions'].append(dict(restarted=container_id, timeout=self.parameters.stop_timeout)) self.results['changed'] = True if not self.check_mode: try: if self.parameters.stop_timeout: dummy = self.client.restart(container_id, timeout=self.parameters.stop_timeout) else: dummy = self.client.restart(container_id) except Exception as exc: self.fail("Error restarting container %s: %s" % (container_id, str(exc))) return self._get_container(container_id) def container_stop(self, container_id): if self.parameters.force_kill: self.container_kill(container_id) return self.results['actions'].append(dict(stopped=container_id, timeout=self.parameters.stop_timeout)) self.results['changed'] = True response = None if not self.check_mode: count = 0 while True: try: if self.parameters.stop_timeout: response = self.client.stop(container_id, timeout=self.parameters.stop_timeout) else: response = self.client.stop(container_id) except APIError as exc: if 'Unpause the container before stopping or killing' in exc.explanation: # New docker daemon versions do not allow containers to be removed # if they are paused. Make sure we don't end up in an infinite loop. if count == 3: self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc))) count += 1 # Unpause try: self.client.unpause(container=container_id) except Exception as exc2: self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2))) # Now try again continue self.fail("Error stopping container %s: %s" % (container_id, str(exc))) except Exception as exc: self.fail("Error stopping container %s: %s" % (container_id, str(exc))) # We only loop when explicitly requested by 'continue' break return response def detect_ipvX_address_usage(client): ''' Helper function to detect whether any specified network uses ipv4_address or ipv6_address ''' for network in client.module.params.get("networks") or []: if network.get('ipv4_address') is not None or network.get('ipv6_address') is not None: return True return False class AnsibleDockerClientContainer(AnsibleDockerClient): # A list of module options which are not docker container properties __NON_CONTAINER_PROPERTY_OPTIONS = tuple([ 'env_file', 'force_kill', 'keep_volumes', 'ignore_image', 'name', 'pull', 'purge_networks', 'recreate', 'restart', 'state', 'trust_image_content', 'networks', 'cleanup', 'kill_signal', 'output_logs', 'paused' ] + list(DOCKER_COMMON_ARGS.keys())) def _parse_comparisons(self): comparisons = {} comp_aliases = {} # Put in defaults explicit_types = dict( command='list', devices='set(dict)', dns_search_domains='list', dns_servers='list', env='set', entrypoint='list', etc_hosts='set', mounts='set(dict)', networks='set(dict)', ulimits='set(dict)', device_read_bps='set(dict)', device_write_bps='set(dict)', device_read_iops='set(dict)', device_write_iops='set(dict)', ) all_options = set() # this is for improving user feedback when a wrong option was specified for comparison default_values = dict( stop_timeout='ignore', ) for option, data in self.module.argument_spec.items(): all_options.add(option) for alias in data.get('aliases', []): all_options.add(alias) # Ignore options which aren't used as container properties if option in self.__NON_CONTAINER_PROPERTY_OPTIONS and option != 'networks': continue # Determine option type if option in explicit_types: datatype = explicit_types[option] elif data['type'] == 'list': datatype = 'set' elif data['type'] == 'dict': datatype = 'dict' else: datatype = 'value' # Determine comparison type if option in default_values: comparison = default_values[option] elif datatype in ('list', 'value'): comparison = 'strict' else: comparison = 'allow_more_present' comparisons[option] = dict(type=datatype, comparison=comparison, name=option) # Keep track of aliases comp_aliases[option] = option for alias in data.get('aliases', []): comp_aliases[alias] = option # Process legacy ignore options if self.module.params['ignore_image']: comparisons['image']['comparison'] = 'ignore' if self.module.params['purge_networks']: comparisons['networks']['comparison'] = 'strict' # Process options if self.module.params.get('comparisons'): # If '*' appears in comparisons, process it first if '*' in self.module.params['comparisons']: value = self.module.params['comparisons']['*'] if value not in ('strict', 'ignore'): self.fail("The wildcard can only be used with comparison modes 'strict' and 'ignore'!") for option, v in comparisons.items(): if option == 'networks': # `networks` is special: only update if # some value is actually specified if self.module.params['networks'] is None: continue v['comparison'] = value # Now process all other comparisons. comp_aliases_used = {} for key, value in self.module.params['comparisons'].items(): if key == '*': continue # Find main key key_main = comp_aliases.get(key) if key_main is None: if key_main in all_options: self.fail("The module option '%s' cannot be specified in the comparisons dict, " "since it does not correspond to container's state!" % key) self.fail("Unknown module option '%s' in comparisons dict!" % key) if key_main in comp_aliases_used: self.fail("Both '%s' and '%s' (aliases of %s) are specified in comparisons dict!" % (key, comp_aliases_used[key_main], key_main)) comp_aliases_used[key_main] = key # Check value and update accordingly if value in ('strict', 'ignore'): comparisons[key_main]['comparison'] = value elif value == 'allow_more_present': if comparisons[key_main]['type'] == 'value': self.fail("Option '%s' is a value and not a set/list/dict, so its comparison cannot be %s" % (key, value)) comparisons[key_main]['comparison'] = value else: self.fail("Unknown comparison mode '%s'!" % value) # Add implicit options comparisons['publish_all_ports'] = dict(type='value', comparison='strict', name='published_ports') comparisons['expected_ports'] = dict(type='dict', comparison=comparisons['published_ports']['comparison'], name='expected_ports') comparisons['disable_healthcheck'] = dict(type='value', comparison='ignore' if comparisons['healthcheck']['comparison'] == 'ignore' else 'strict', name='disable_healthcheck') # Check legacy values if self.module.params['ignore_image'] and comparisons['image']['comparison'] != 'ignore': self.module.warn('The ignore_image option has been overridden by the comparisons option!') if self.module.params['purge_networks'] and comparisons['networks']['comparison'] != 'strict': self.module.warn('The purge_networks option has been overridden by the comparisons option!') self.comparisons = comparisons def _get_additional_minimal_versions(self): stop_timeout_supported = self.docker_api_version >= LooseVersion('1.25') stop_timeout_needed_for_update = self.module.params.get("stop_timeout") is not None and self.module.params.get('state') != 'absent' if stop_timeout_supported: stop_timeout_supported = self.docker_py_version >= LooseVersion('2.1') if stop_timeout_needed_for_update and not stop_timeout_supported: # We warn (instead of fail) since in older versions, stop_timeout was not used # to update the container's configuration, but only when stopping a container. self.module.warn("Docker SDK for Python's version is %s. Minimum version required is 2.1 to update " "the container's stop_timeout configuration. " "If you use the 'docker-py' module, you have to switch to the 'docker' Python package." % (docker_version,)) else: if stop_timeout_needed_for_update and not stop_timeout_supported: # We warn (instead of fail) since in older versions, stop_timeout was not used # to update the container's configuration, but only when stopping a container. self.module.warn("Docker API version is %s. Minimum version required is 1.25 to set or " "update the container's stop_timeout configuration." % (self.docker_api_version_str,)) self.option_minimal_versions['stop_timeout']['supported'] = stop_timeout_supported def __init__(self, **kwargs): option_minimal_versions = dict( # internal options log_config=dict(), publish_all_ports=dict(), ports=dict(), volume_binds=dict(), name=dict(), # normal options device_read_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_read_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_write_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_write_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'), dns_opts=dict(docker_api_version='1.21', docker_py_version='1.10.0'), ipc_mode=dict(docker_api_version='1.25'), mac_address=dict(docker_api_version='1.25'), oom_score_adj=dict(docker_api_version='1.22'), shm_size=dict(docker_api_version='1.22'), stop_signal=dict(docker_api_version='1.21'), tmpfs=dict(docker_api_version='1.22'), volume_driver=dict(docker_api_version='1.21'), memory_reservation=dict(docker_api_version='1.21'), kernel_memory=dict(docker_api_version='1.21'), auto_remove=dict(docker_py_version='2.1.0', docker_api_version='1.25'), healthcheck=dict(docker_py_version='2.0.0', docker_api_version='1.24'), init=dict(docker_py_version='2.2.0', docker_api_version='1.25'), runtime=dict(docker_py_version='2.4.0', docker_api_version='1.25'), sysctls=dict(docker_py_version='1.10.0', docker_api_version='1.24'), userns_mode=dict(docker_py_version='1.10.0', docker_api_version='1.23'), uts=dict(docker_py_version='3.5.0', docker_api_version='1.25'), pids_limit=dict(docker_py_version='1.10.0', docker_api_version='1.23'), mounts=dict(docker_py_version='2.6.0', docker_api_version='1.25'), # specials ipvX_address_supported=dict(docker_py_version='1.9.0', docker_api_version='1.22', detect_usage=detect_ipvX_address_usage, usage_msg='ipv4_address or ipv6_address in networks'), stop_timeout=dict(), # see _get_additional_minimal_versions() ) super(AnsibleDockerClientContainer, self).__init__( option_minimal_versions=option_minimal_versions, option_minimal_versions_ignore_params=self.__NON_CONTAINER_PROPERTY_OPTIONS, **kwargs ) self.image_inspect_source = 'Config' if self.docker_api_version < LooseVersion('1.21'): self.image_inspect_source = 'ContainerConfig' self._get_additional_minimal_versions() self._parse_comparisons() def main(): argument_spec = dict( auto_remove=dict(type='bool', default=False), blkio_weight=dict(type='int'), capabilities=dict(type='list', elements='str'), cap_drop=dict(type='list', elements='str'), cleanup=dict(type='bool', default=False), command=dict(type='raw'), comparisons=dict(type='dict'), cpu_period=dict(type='int'), cpu_quota=dict(type='int'), cpuset_cpus=dict(type='str'), cpuset_mems=dict(type='str'), cpu_shares=dict(type='int'), detach=dict(type='bool', default=True), devices=dict(type='list', elements='str'), device_read_bps=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='str'), )), device_write_bps=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='str'), )), device_read_iops=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='int'), )), device_write_iops=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='int'), )), dns_servers=dict(type='list', elements='str'), dns_opts=dict(type='list', elements='str'), dns_search_domains=dict(type='list', elements='str'), domainname=dict(type='str'), entrypoint=dict(type='list', elements='str'), env=dict(type='dict'), env_file=dict(type='path'), etc_hosts=dict(type='dict'), exposed_ports=dict(type='list', elements='str', aliases=['exposed', 'expose']), force_kill=dict(type='bool', default=False, aliases=['forcekill']), groups=dict(type='list', elements='str'), healthcheck=dict(type='dict', options=dict( test=dict(type='raw'), interval=dict(type='str'), timeout=dict(type='str'), start_period=dict(type='str'), retries=dict(type='int'), )), hostname=dict(type='str'), ignore_image=dict(type='bool', default=False), image=dict(type='str'), init=dict(type='bool', default=False), interactive=dict(type='bool', default=False), ipc_mode=dict(type='str'), keep_volumes=dict(type='bool', default=True), kernel_memory=dict(type='str'), kill_signal=dict(type='str'), labels=dict(type='dict'), links=dict(type='list', elements='str'), log_driver=dict(type='str'), log_options=dict(type='dict', aliases=['log_opt']), mac_address=dict(type='str'), memory=dict(type='str', default='0'), memory_reservation=dict(type='str'), memory_swap=dict(type='str'), memory_swappiness=dict(type='int'), mounts=dict(type='list', elements='dict', options=dict( target=dict(type='str', required=True), source=dict(type='str'), type=dict(type='str', choices=['bind', 'volume', 'tmpfs', 'npipe'], default='volume'), read_only=dict(type='bool'), consistency=dict(type='str', choices=['default', 'consistent', 'cached', 'delegated']), propagation=dict(type='str', choices=['private', 'rprivate', 'shared', 'rshared', 'slave', 'rslave']), no_copy=dict(type='bool'), labels=dict(type='dict'), volume_driver=dict(type='str'), volume_options=dict(type='dict'), tmpfs_size=dict(type='str'), tmpfs_mode=dict(type='str'), )), name=dict(type='str', required=True), network_mode=dict(type='str'), networks=dict(type='list', elements='dict', options=dict( name=dict(type='str', required=True), ipv4_address=dict(type='str'), ipv6_address=dict(type='str'), aliases=dict(type='list', elements='str'), links=dict(type='list', elements='str'), )), networks_cli_compatible=dict(type='bool'), oom_killer=dict(type='bool'), oom_score_adj=dict(type='int'), output_logs=dict(type='bool', default=False), paused=dict(type='bool', default=False), pid_mode=dict(type='str'), pids_limit=dict(type='int'), privileged=dict(type='bool', default=False), published_ports=dict(type='list', elements='str', aliases=['ports']), pull=dict(type='bool', default=False), purge_networks=dict(type='bool', default=False), read_only=dict(type='bool', default=False), recreate=dict(type='bool', default=False), restart=dict(type='bool', default=False), restart_policy=dict(type='str', choices=['no', 'on-failure', 'always', 'unless-stopped']), restart_retries=dict(type='int'), runtime=dict(type='str'), security_opts=dict(type='list', elements='str'), shm_size=dict(type='str'), state=dict(type='str', default='started', choices=['absent', 'present', 'started', 'stopped']), stop_signal=dict(type='str'), stop_timeout=dict(type='int'), sysctls=dict(type='dict'), tmpfs=dict(type='list', elements='str'), trust_image_content=dict(type='bool', default=False, removed_in_version='2.14'), tty=dict(type='bool', default=False), ulimits=dict(type='list', elements='str'), user=dict(type='str'), userns_mode=dict(type='str'), uts=dict(type='str'), volume_driver=dict(type='str'), volumes=dict(type='list', elements='str'), volumes_from=dict(type='list', elements='str'), working_dir=dict(type='str'), ) required_if = [ ('state', 'present', ['image']) ] client = AnsibleDockerClientContainer( argument_spec=argument_spec, required_if=required_if, supports_check_mode=True, min_docker_api_version='1.20', ) if client.module.params['networks_cli_compatible'] is None and client.module.params['networks']: client.module.deprecate( 'Please note that docker_container handles networks slightly different than docker CLI. ' 'If you specify networks, the default network will still be attached as the first network. ' '(You can specify purge_networks to remove all networks not explicitly listed.) ' 'This behavior will change in Ansible 2.12. You can change the behavior now by setting ' 'the new `networks_cli_compatible` option to `yes`, and remove this warning by setting ' 'it to `no`', version='2.12' ) try: cm = ContainerManager(client) client.module.exit_json(**sanitize_result(cm.results)) except DockerException as e: client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc()) except RequestException as e: client.fail('An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'.format(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,914
Add Redfish commands to set boot order and set boot order back to default
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> Add new commands to the Redfish remote_management modules to allow setting the boot order and to set the order back to the default. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_config.py redfish_utils.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Operators need a way to change the boot order on Redfish systems and to set the boot order back to the default order. There is currently no way to do that with the Redfish modules. <!--- Paste example playbooks or commands between quotes below --> Proposed playbook snippets: ```yaml - name: Set boot order redfish_config: category: Systems command: SetBootOrder boot_order: - Boot0002 - Boot0001 - Boot0000 - Boot0003 - Boot0004 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` ```yaml - name: Set boot order to the default redfish_config: category: Systems command: SetDefaultBootOrder baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/63914
https://github.com/ansible/ansible/pull/63915
16d4d2dba9d62103a198647894f7f82020dca27c
2b8553b242c270fa8207b251b3faf8cf4edbbc85
2019-10-24T16:45:06Z
python
2019-10-29T13:10:58Z
lib/ansible/module_utils/redfish_utils.py
# Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import json from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import http_client from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} class RedfishUtils(object): def __init__(self, creds, root_uri, timeout, module): self.root_uri = root_uri self.creds = creds self.timeout = timeout self.module = module self.service_root = '/redfish/v1/' self._init_session() # The following functions are to send GET/POST/PATCH/DELETE requests def get_request(self, uri): try: resp = open_url(uri, method="GET", headers=GET_HEADERS, url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) data = json.loads(resp.read()) headers = dict((k.lower(), v) for (k, v) in resp.info().items()) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'data': data, 'headers': headers} def post_request(self, uri, pyld): try: resp = open_url(uri, data=json.dumps(pyld), headers=POST_HEADERS, method="POST", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def patch_request(self, uri, pyld): headers = PATCH_HEADERS r = self.get_request(uri) if r['ret']: # Get etag from etag header or @odata.etag property etag = r['headers'].get('etag') if not etag: etag = r['data'].get('@odata.etag') if etag: # Make copy of headers and add If-Match header headers = dict(headers) headers['If-Match'] = etag try: resp = open_url(uri, data=json.dumps(pyld), headers=headers, method="PATCH", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def delete_request(self, uri, pyld=None): try: data = json.dumps(pyld) if pyld else None resp = open_url(uri, data=data, headers=DELETE_HEADERS, method="DELETE", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} @staticmethod def _get_extended_message(error): """ Get Redfish ExtendedInfo message from response payload if present :param error: an HTTPError exception :type error: HTTPError :return: the ExtendedInfo message if present, else standard HTTP error """ msg = http_client.responses.get(error.code, '') if error.code >= 400: try: body = error.read().decode('utf-8') data = json.loads(body) ext_info = data['error']['@Message.ExtendedInfo'] msg = ext_info[0]['Message'] except Exception: pass return msg def _init_session(self): pass def _find_accountservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} else: account_service = data["AccountService"]["@odata.id"] response = self.get_request(self.root_uri + account_service) if response['ret'] is False: return response data = response['data'] accounts = data['Accounts']['@odata.id'] if accounts[-1:] == '/': accounts = accounts[:-1] self.accounts_uri = accounts return {'ret': True} def _find_sessionservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'SessionService' not in data: return {'ret': False, 'msg': "SessionService resource not found"} else: session_service = data["SessionService"]["@odata.id"] response = self.get_request(self.root_uri + session_service) if response['ret'] is False: return response data = response['data'] sessions = data['Sessions']['@odata.id'] if sessions[-1:] == '/': sessions = sessions[:-1] self.sessions_uri = sessions return {'ret': True} def _find_systems_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Systems' not in data: return {'ret': False, 'msg': "Systems resource not found"} response = self.get_request(self.root_uri + data['Systems']['@odata.id']) if response['ret'] is False: return response self.systems_uris = [ i['@odata.id'] for i in response['data'].get('Members', [])] if not self.systems_uris: return { 'ret': False, 'msg': "ComputerSystem's Members array is either empty or missing"} return {'ret': True} def _find_updateservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'UpdateService' not in data: return {'ret': False, 'msg': "UpdateService resource not found"} else: update = data["UpdateService"]["@odata.id"] self.update_uri = update response = self.get_request(self.root_uri + update) if response['ret'] is False: return response data = response['data'] firmware_inventory = data['FirmwareInventory'][u'@odata.id'] self.firmware_uri = firmware_inventory return {'ret': True} def _find_chassis_resource(self): chassis_service = [] response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Chassis' not in data: return {'ret': False, 'msg': "Chassis resource not found"} else: chassis = data["Chassis"]["@odata.id"] response = self.get_request(self.root_uri + chassis) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: chassis_service.append(member[u'@odata.id']) self.chassis_uri_list = chassis_service return {'ret': True} def _find_managers_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Managers' not in data: return {'ret': False, 'msg': "Manager resource not found"} else: manager = data["Managers"]["@odata.id"] response = self.get_request(self.root_uri + manager) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: manager_service = member[u'@odata.id'] self.manager_uri = manager_service return {'ret': True} def get_logs(self): log_svcs_uri_list = [] list_of_logs = [] properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat', 'Message', 'MessageId', 'MessageArgs'] # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data.get('Members', []): response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id']) if response['ret'] is False: return response _data = response['data'] if 'Entries' in _data: log_svcs_uri_list.append(_data['Entries'][u'@odata.id']) # For each entry in LogServices, get log name and all log entries for log_svcs_uri in log_svcs_uri_list: logs = {} list_of_log_entries = [] response = self.get_request(self.root_uri + log_svcs_uri) if response['ret'] is False: return response data = response['data'] logs['Description'] = data.get('Description', 'Collection of log entries') # Get all log entries for each type of log found for logEntry in data.get('Members', []): entry = {} for prop in properties: if prop in logEntry: entry[prop] = logEntry.get(prop) if entry: list_of_log_entries.append(entry) log_name = log_svcs_uri.split('/')[-1] logs[log_name] = list_of_log_entries list_of_logs.append(logs) # list_of_logs[logs{list_of_log_entries[entry{}]}] return {'ret': True, 'entries': list_of_logs} def clear_logs(self): # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data[u'Members']: response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"]) if response['ret'] is False: return response _data = response['data'] # Check to make sure option is available, otherwise error is ugly if "Actions" in _data: if "#LogService.ClearLog" in _data[u"Actions"]: self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {}) if response['ret'] is False: return response return {'ret': True} def aggregate(self, func): ret = True entries = [] for systems_uri in self.systems_uris: inventory = func(systems_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'systems_uri': systems_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_storage_controller_inventory(self, systems_uri): result = {} controller_list = [] controller_results = [] # Get these entries, but does not fail if not found properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers', 'Location', 'Manufacturer', 'Model', 'Name', 'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status'] key = "StorageControllers" # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'Storage' not in data: return {'ret': False, 'msg': "Storage resource not found"} # Get a list of all storage controllers and build respective URIs storage_uri = data['Storage']["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Loop through Members and their StorageControllers # and gather properties from each StorageController if data[u'Members']: for storage_member in data[u'Members']: storage_member_uri = storage_member[u'@odata.id'] response = self.get_request(self.root_uri + storage_member_uri) data = response['data'] if key in data: controller_list = data[key] for controller in controller_list: controller_result = {} for property in properties: if property in controller: controller_result[property] = controller[property] controller_results.append(controller_result) result['entries'] = controller_results return result else: return {'ret': False, 'msg': "Storage resource not found"} def get_multi_storage_controller_inventory(self): return self.aggregate(self.get_storage_controller_inventory) def get_disk_inventory(self, systems_uri): result = {'entries': []} controller_list = [] disk_results = [] # Get these entries, but does not fail if not found properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes', 'EncryptionAbility', 'EncryptionStatus', 'FailurePredicted', 'HotspareType', 'Id', 'Identifiers', 'Manufacturer', 'MediaType', 'Model', 'Name', 'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision', 'RotationSpeedRPM', 'SerialNumber', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data[u'Members']: for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Drives' in data: for device in data[u'Drives']: disk_uri = self.root_uri + device[u'@odata.id'] response = self.get_request(disk_uri) data = response['data'] disk_result = {} for property in properties: if property in data: if data[property] is not None: disk_result[property] = data[property] disk_results.append(disk_result) result["entries"].append(disk_results) if 'SimpleStorage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data["SimpleStorage"]["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for device in data[u'Devices']: disk_result = {} for property in properties: if property in device: disk_result[property] = device[property] disk_results.append(disk_result) result["entries"].append(disk_results) return result def get_multi_disk_inventory(self): return self.aggregate(self.get_disk_inventory) def get_volume_inventory(self, systems_uri): result = {'entries': []} controller_list = [] volume_list = [] volume_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes', 'Capacity', 'CapacityBytes', 'CapacitySources', 'Encrypted', 'EncryptionTypes', 'Identifiers', 'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities', 'AllocatedPools', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data.get('Members'): for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Volumes' in data: # Get a list of all volumes and build respective URIs volumes_uri = data[u'Volumes'][u'@odata.id'] response = self.get_request(self.root_uri + volumes_uri) data = response['data'] if data.get('Members'): for volume in data[u'Members']: volume_list.append(volume[u'@odata.id']) for v in volume_list: uri = self.root_uri + v response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] volume_result = {} for property in properties: if property in data: if data[property] is not None: volume_result[property] = data[property] # Get related Drives Id drive_id_list = [] if 'Links' in data: if 'Drives' in data[u'Links']: for link in data[u'Links'][u'Drives']: drive_id_link = link[u'@odata.id'] drive_id = drive_id_link.split("/")[-1] drive_id_list.append({'Id': drive_id}) volume_result['Linked_drives'] = drive_id_list volume_results.append(volume_result) result["entries"].append(volume_results) else: return {'ret': False, 'msg': "Storage resource not found"} return result def get_multi_volume_inventory(self): return self.aggregate(self.get_volume_inventory) def restart_manager_gracefully(self): result = {} key = "Actions" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] action_uri = data[key]["#Manager.Reset"]["target"] payload = {'ResetType': 'GracefulRestart'} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True} def manage_indicator_led(self, command): result = {} key = 'IndicatorLED' payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'} result = {} for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} if command in payloads.keys(): payload = {'IndicatorLED': payloads[command]} response = self.patch_request(self.root_uri + chassis_uri, payload) if response['ret'] is False: return response else: return {'ret': False, 'msg': 'Invalid command'} return result def _map_reset_type(self, reset_type, allowable_values): equiv_types = { 'On': 'ForceOn', 'ForceOn': 'On', 'ForceOff': 'GracefulShutdown', 'GracefulShutdown': 'ForceOff', 'GracefulRestart': 'ForceRestart', 'ForceRestart': 'GracefulRestart' } if reset_type in allowable_values: return reset_type if reset_type not in equiv_types: return reset_type mapped_type = equiv_types[reset_type] if mapped_type in allowable_values: return mapped_type return reset_type def manage_system_power(self, command): key = "Actions" reset_type_values = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] # command should be PowerOn, PowerForceOff, etc. if not command.startswith('Power'): return {'ret': False, 'msg': 'Invalid Command (%s)' % command} reset_type = command[5:] # map Reboot to a ResetType that does a reboot if reset_type == 'Reboot': reset_type = 'GracefulRestart' if reset_type not in reset_type_values: return {'ret': False, 'msg': 'Invalid Command (%s)' % command} # read the system resource and get the current power state response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response data = response['data'] power_state = data.get('PowerState') # if power is already in target state, nothing to do if power_state == "On" and reset_type in ['On', 'ForceOn']: return {'ret': True, 'changed': False} if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']: return {'ret': True, 'changed': False} # get the #ComputerSystem.Reset Action and target URI if key not in data or '#ComputerSystem.Reset' not in data[key]: return {'ret': False, 'msg': 'Action #ComputerSystem.Reset not found'} reset_action = data[key]['#ComputerSystem.Reset'] if 'target' not in reset_action: return {'ret': False, 'msg': 'target URI missing from Action #ComputerSystem.Reset'} action_uri = reset_action['target'] # get AllowableValues from ActionInfo allowable_values = None if '@Redfish.ActionInfo' in reset_action: action_info_uri = reset_action.get('@Redfish.ActionInfo') response = self.get_request(self.root_uri + action_info_uri) if response['ret'] is True: data = response['data'] if 'Parameters' in data: params = data['Parameters'] for param in params: if param.get('Name') == 'ResetType': allowable_values = param.get('AllowableValues') break # fallback to @Redfish.AllowableValues annotation if allowable_values is None: allowable_values = reset_action.get('[email protected]', []) # map ResetType to an allowable value if needed if reset_type not in allowable_values: reset_type = self._map_reset_type(reset_type, allowable_values) # define payload payload = {'ResetType': reset_type} # POST to Action URI response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def _find_account_uri(self, username=None, acct_id=None): if not any((username, acct_id)): return {'ret': False, 'msg': 'Must provide either account_id or account_username'} response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if username: if username == data.get('UserName'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} if acct_id: if acct_id == data.get('Id'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No account with the given account_id or account_username found'} def _find_empty_account_slot(self): response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] if uris: # first slot may be reserved, so move to end of list uris += [uris.pop(0)] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if data.get('UserName') == "" and not data.get('Enabled', True): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No empty account slot found'} def list_users(self): result = {} # listing all users has always been slower than other operations, why? user_list = [] users_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled'] response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for users in data.get('Members', []): user_list.append(users[u'@odata.id']) # user_list[] are URIs # for each user, get details for uri in user_list: user = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: user[property] = data[property] users_results.append(user) result["entries"] = users_results return result def add_user_via_patch(self, user): if user.get('account_id'): # If Id slot specified, use it response = self._find_account_uri(acct_id=user.get('account_id')) else: # Otherwise find first empty slot response = self._find_empty_account_slot() if not response['ret']: return response uri = response['uri'] payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def add_user(self, user): if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_account_uri(username=user.get('account_username')) if response['ret']: # account_username already exists, nothing to do return {'ret': True, 'changed': False} response = self.get_request(self.root_uri + self.accounts_uri) if not response['ret']: return response headers = response['headers'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'POST' not in methods: # if Allow header present and POST not listed, add via PATCH return self.add_user_via_patch(user) payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.post_request(self.root_uri + self.accounts_uri, payload) if not response['ret']: if response.get('status') == 405: # if POST returned a 405, try to add via PATCH return self.add_user_via_patch(user) else: return response return {'ret': True} def enable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('Enabled'): # account already enabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': True} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user_via_patch(self, user, uri=None, data=None): if not uri: response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data and data.get('UserName') == '' and not data.get('Enabled', False): # account UserName already cleared, nothing to do return {'ret': True, 'changed': False} payload = {'UserName': ''} if 'Enabled' in data: payload['Enabled'] = False response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: if response.get('no_match'): # account does not exist, nothing to do return {'ret': True, 'changed': False} else: # some error encountered return response uri = response['uri'] headers = response['headers'] data = response['data'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'DELETE' not in methods: # if Allow header present and DELETE not listed, del via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) response = self.delete_request(self.root_uri + uri) if not response['ret']: if response.get('status') == 405: # if DELETE returned a 405, try to delete via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) else: return response return {'ret': True} def disable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if not data.get('Enabled'): # account already disabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': False} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_role(self, user): if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('RoleId') == user.get('account_roleid'): # account already has RoleId , nothing to do return {'ret': True, 'changed': False} payload = {'RoleId': user.get('account_roleid')} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_password(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'Password': user['account_password']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def get_sessions(self): result = {} # listing all users has always been slower than other operations, why? session_list = [] sessions_results = [] # Get these entries, but does not fail if not found properties = ['Description', 'Id', 'Name', 'UserName'] response = self.get_request(self.root_uri + self.sessions_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for sessions in data[u'Members']: session_list.append(sessions[u'@odata.id']) # session_list[] are URIs # for each session, get details for uri in session_list: session = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: session[property] = data[property] sessions_results.append(session) result["entries"] = sessions_results return result def get_firmware_update_capabilities(self): result = {} response = self.get_request(self.root_uri + self.update_uri) if response['ret'] is False: return response result['ret'] = True result['entries'] = {} data = response['data'] if "Actions" in data: actions = data['Actions'] if len(actions) > 0: for key in actions.keys(): action = actions.get(key) if 'title' in action: title = action['title'] else: title = key result['entries'][title] = action.get('[email protected]', ["Key [email protected] not found"]) else: return {'ret': "False", 'msg': "Actions list is empty."} else: return {'ret': "False", 'msg': "Key Actions not found."} return result def get_firmware_inventory(self): result = {} response = self.get_request(self.root_uri + self.firmware_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] result['entries'] = [] for device in data[u'Members']: uri = self.root_uri + device[u'@odata.id'] # Get details for each device response = self.get_request(uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] firmware = {} # Get these standard properties if present for key in ['Name', 'Id', 'Status', 'Version', 'Updateable', 'SoftwareId', 'LowestSupportedVersion', 'Manufacturer', 'ReleaseDate']: if key in data: firmware[key] = data.get(key) result['entries'].append(firmware) return result def get_bios_attributes(self, systems_uri): result = {} bios_attributes = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for attribute in data[u'Attributes'].items(): bios_attributes[attribute[0]] = attribute[1] result["entries"] = bios_attributes return result def get_multi_bios_attributes(self): return self.aggregate(self.get_bios_attributes) def get_boot_order(self, systems_uri): result = {} # Get these entries from BootOption, if present properties = ['DisplayName', 'BootOptionReference'] # Retrieve System resource response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] # Retrieve BootOptions if present if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']: boot_options_uri = boot['BootOptions']["@odata.id"] # Get BootOptions resource response = self.get_request(self.root_uri + boot_options_uri) if response['ret'] is False: return response data = response['data'] # Retrieve Members array if 'Members' not in data: return {'ret': False, 'msg': "Members not found in BootOptionsCollection"} members = data['Members'] else: members = [] # Build dict of BootOptions keyed by BootOptionReference boot_options_dict = {} for member in members: if '@odata.id' not in member: return {'ret': False, 'msg': "@odata.id not found in BootOptions"} boot_option_uri = member['@odata.id'] response = self.get_request(self.root_uri + boot_option_uri) if response['ret'] is False: return response data = response['data'] if 'BootOptionReference' not in data: return {'ret': False, 'msg': "BootOptionReference not found in BootOption"} boot_option_ref = data['BootOptionReference'] # fetch the props to display for this boot device boot_props = {} for prop in properties: if prop in data: boot_props[prop] = data[prop] boot_options_dict[boot_option_ref] = boot_props # Build boot device list boot_device_list = [] for ref in boot_order: boot_device_list.append( boot_options_dict.get(ref, {'BootOptionReference': ref})) result["entries"] = boot_device_list return result def get_multi_boot_order(self): return self.aggregate(self.get_boot_order) def get_boot_override(self, systems_uri): result = {} properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget", "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "[email protected]"] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Boot' not in data: return {'ret': False, 'msg': "Key Boot not found"} boot = data['Boot'] boot_overrides = {} if "BootSourceOverrideEnabled" in boot: if boot["BootSourceOverrideEnabled"] is not False: for property in properties: if property in boot: if boot[property] is not None: boot_overrides[property] = boot[property] else: return {'ret': False, 'msg': "No boot override is enabled."} result['entries'] = boot_overrides return result def get_multi_boot_override(self): return self.aggregate(self.get_boot_override) def set_bios_default_settings(self): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] reset_bios_settings_uri = data["Actions"]["#Bios.ResetBios"]["target"] response = self.post_request(self.root_uri + reset_bios_settings_uri, {}) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Set BIOS to default settings"} def set_one_time_boot_device(self, bootdevice, uefi_target, boot_next): result = {} key = "Boot" if not bootdevice: return {'ret': False, 'msg': "bootdevice option required for SetOneTimeBoot"} # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} boot = data[key] annotation = '[email protected]' if annotation in boot: allowable_values = boot[annotation] if isinstance(allowable_values, list) and bootdevice not in allowable_values: return {'ret': False, 'msg': "Boot device %s not in list of allowable values (%s)" % (bootdevice, allowable_values)} # read existing values enabled = boot.get('BootSourceOverrideEnabled') target = boot.get('BootSourceOverrideTarget') cur_uefi_target = boot.get('UefiTargetBootSourceOverride') cur_boot_next = boot.get('BootNext') if bootdevice == 'UefiTarget': if not uefi_target: return {'ret': False, 'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"} if enabled == 'Once' and target == bootdevice and uefi_target == cur_uefi_target: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'UefiTargetBootSourceOverride': uefi_target } } elif bootdevice == 'UefiBootNext': if not boot_next: return {'ret': False, 'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"} if enabled == 'Once' and target == bootdevice and boot_next == cur_boot_next: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'BootNext': boot_next } } else: if enabled == 'Once' and target == bootdevice: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice } } response = self.patch_request(self.root_uri + self.systems_uris[0], payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def set_bios_attributes(self, attr): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # First, check if BIOS attribute exists if attr['bios_attr_name'] not in data[u'Attributes']: return {'ret': False, 'msg': "BIOS attribute not found"} # Find out if value is already set to what we want. If yes, return if data[u'Attributes'][attr['bios_attr_name']] == attr['bios_attr_value']: return {'ret': True, 'changed': False, 'msg': "BIOS attribute already set"} set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"]["@odata.id"] # Example: bios_attr = {\"name\":\"value\"} bios_attr = "{\"" + attr['bios_attr_name'] + "\":\"" + attr['bios_attr_value'] + "\"}" payload = {"Attributes": json.loads(bios_attr)} response = self.patch_request(self.root_uri + set_bios_attr_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified BIOS attribute"} def get_chassis_inventory(self): result = {} chassis_results = [] # Get these entries, but does not fail if not found properties = ['ChassisType', 'PartNumber', 'AssetTag', 'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] chassis_result = {} for property in properties: if property in data: chassis_result[property] = data[property] chassis_results.append(chassis_result) result["entries"] = chassis_results return result def get_fan_inventory(self): result = {} fan_results = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['FanName', 'Reading', 'ReadingUnits', 'Status'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: # match: found an entry for "Thermal" information = fans thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for device in data[u'Fans']: fan = {} for property in properties: if property in device: fan[property] = device[property] fan_results.append(fan) result["entries"] = fan_results return result def get_chassis_power(self): result = {} key = "Power" # Get these entries, but does not fail if not found properties = ['Name', 'PowerAllocatedWatts', 'PowerAvailableWatts', 'PowerCapacityWatts', 'PowerConsumedWatts', 'PowerMetrics', 'PowerRequestedWatts', 'RelatedItem', 'Status'] chassis_power_results = [] # Go through list for chassis_uri in self.chassis_uri_list: chassis_power_result = {} response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: response = self.get_request(self.root_uri + data[key]['@odata.id']) data = response['data'] if 'PowerControl' in data: if len(data['PowerControl']) > 0: data = data['PowerControl'][0] for property in properties: if property in data: chassis_power_result[property] = data[property] else: return {'ret': False, 'msg': 'Key PowerControl not found.'} chassis_power_results.append(chassis_power_result) else: return {'ret': False, 'msg': 'Key Power not found.'} result['entries'] = chassis_power_results return result def get_chassis_thermals(self): result = {} sensors = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical', 'UpperThresholdFatal', 'UpperThresholdNonCritical', 'LowerThresholdCritical', 'LowerThresholdFatal', 'LowerThresholdNonCritical', 'MaxReadingRangeTemp', 'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem', 'SensorNumber'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if "Temperatures" in data: for sensor in data[u'Temperatures']: sensor_result = {} for property in properties: if property in sensor: if sensor[property] is not None: sensor_result[property] = sensor[property] sensors.append(sensor_result) if sensors is None: return {'ret': False, 'msg': 'Key Temperatures was not found.'} result['entries'] = sensors return result def get_cpu_inventory(self, systems_uri): result = {} cpu_list = [] cpu_results = [] key = "Processors" # Get these entries, but does not fail if not found properties = ['Id', 'Manufacturer', 'Model', 'MaxSpeedMHz', 'TotalCores', 'TotalThreads', 'Status'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} processors_uri = data[key]["@odata.id"] # Get a list of all CPUs and build respective URIs response = self.get_request(self.root_uri + processors_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for cpu in data[u'Members']: cpu_list.append(cpu[u'@odata.id']) for c in cpu_list: cpu = {} uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: cpu[property] = data[property] cpu_results.append(cpu) result["entries"] = cpu_results return result def get_multi_cpu_inventory(self): return self.aggregate(self.get_cpu_inventory) def get_memory_inventory(self, systems_uri): result = {} memory_list = [] memory_results = [] key = "Memory" # Get these entries, but does not fail if not found properties = ['SerialNumber', 'MemoryDeviceType', 'PartNuber', 'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} memory_uri = data[key]["@odata.id"] # Get a list of all DIMMs and build respective URIs response = self.get_request(self.root_uri + memory_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for dimm in data[u'Members']: memory_list.append(dimm[u'@odata.id']) for m in memory_list: dimm = {} uri = self.root_uri + m response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if "Status" in data: if "State" in data["Status"]: if data["Status"]["State"] == "Absent": continue else: continue for property in properties: if property in data: dimm[property] = data[property] memory_results.append(dimm) result["entries"] = memory_results return result def get_multi_memory_inventory(self): return self.aggregate(self.get_memory_inventory) def get_nic_inventory(self, resource_uri): result = {} nic_list = [] nic_results = [] key = "EthernetInterfaces" # Get these entries, but does not fail if not found properties = ['Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses', 'NameServers', 'MACAddress', 'PermanentMACAddress', 'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} ethernetinterfaces_uri = data[key]["@odata.id"] # Get a list of all network controllers and build respective URIs response = self.get_request(self.root_uri + ethernetinterfaces_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for nic in data[u'Members']: nic_list.append(nic[u'@odata.id']) for n in nic_list: nic = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: nic[property] = data[property] nic_results.append(nic) result["entries"] = nic_results return result def get_multi_nic_inventory(self, resource_type): ret = True entries = [] # Given resource_type, use the proper URI if resource_type == 'Systems': resource_uris = self.systems_uris elif resource_type == 'Manager': # put in a list to match what we're doing with systems_uris resource_uris = [self.manager_uri] for resource_uri in resource_uris: inventory = self.get_nic_inventory(resource_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'resource_uri': resource_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_virtualmedia(self, resource_uri): result = {} virtualmedia_list = [] virtualmedia_results = [] key = "VirtualMedia" # Get these entries, but does not fail if not found properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes', 'Image', 'ImageName', 'Name', 'WriteProtected', 'TransferMethod', 'TransferProtocolType'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} virtualmedia_uri = data[key]["@odata.id"] # Get a list of all virtual media and build respective URIs response = self.get_request(self.root_uri + virtualmedia_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for virtualmedia in data[u'Members']: virtualmedia_list.append(virtualmedia[u'@odata.id']) for n in virtualmedia_list: virtualmedia = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: virtualmedia[property] = data[property] virtualmedia_results.append(virtualmedia) result["entries"] = virtualmedia_results return result def get_multi_virtualmedia(self): ret = True entries = [] # Because _find_managers_resource() only find last Manager uri in self.manager_uri, not one list. This should be 1 issue. # I have to put manager_uri into list to reduce future changes when the issue is fixed. resource_uris = [self.manager_uri] for resource_uri in resource_uris: virtualmedia = self.get_virtualmedia(resource_uri) ret = virtualmedia.pop('ret') and ret if 'entries' in virtualmedia: entries.append(({'resource_uri': resource_uri}, virtualmedia['entries'])) return dict(ret=ret, entries=entries) def get_psu_inventory(self): result = {} psu_list = [] psu_results = [] key = "PowerSupplies" # Get these entries, but does not fail if not found properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status'] # Get a list of all Chassis and build URIs, then get all PowerSupplies # from each Power entry in the Chassis chassis_uri_list = self.chassis_uri_list for chassis_uri in chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Power' in data: power_uri = data[u'Power'][u'@odata.id'] else: continue response = self.get_request(self.root_uri + power_uri) data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} psu_list = data[key] for psu in psu_list: psu_not_present = False psu_data = {} for property in properties: if property in psu: if psu[property] is not None: if property == 'Status': if 'State' in psu[property]: if psu[property]['State'] == 'Absent': psu_not_present = True psu_data[property] = psu[property] if psu_not_present: continue psu_results.append(psu_data) result["entries"] = psu_results if not result["entries"]: return {'ret': False, 'msg': "No PowerSupply objects found"} return result def get_multi_psu_inventory(self): return self.aggregate(self.get_psu_inventory) def get_system_inventory(self, systems_uri): result = {} inventory = {} # Get these entries, but does not fail if not found properties = ['Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag', 'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary', 'ProcessorSummary', 'TrustedModules'] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for property in properties: if property in data: inventory[property] = data[property] result["entries"] = inventory return result def get_multi_system_inventory(self): return self.aggregate(self.get_system_inventory)
closed
ansible/ansible
https://github.com/ansible/ansible
63,914
Add Redfish commands to set boot order and set boot order back to default
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> Add new commands to the Redfish remote_management modules to allow setting the boot order and to set the order back to the default. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_config.py redfish_utils.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Operators need a way to change the boot order on Redfish systems and to set the boot order back to the default order. There is currently no way to do that with the Redfish modules. <!--- Paste example playbooks or commands between quotes below --> Proposed playbook snippets: ```yaml - name: Set boot order redfish_config: category: Systems command: SetBootOrder boot_order: - Boot0002 - Boot0001 - Boot0000 - Boot0003 - Boot0004 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` ```yaml - name: Set boot order to the default redfish_config: category: Systems command: SetDefaultBootOrder baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/63914
https://github.com/ansible/ansible/pull/63915
16d4d2dba9d62103a198647894f7f82020dca27c
2b8553b242c270fa8207b251b3faf8cf4edbbc85
2019-10-24T16:45:06Z
python
2019-10-29T13:10:58Z
lib/ansible/modules/remote_management/redfish/redfish_config.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_config version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to set or update a configuration attribute. - Manages BIOS configuration settings. - Manages OOB controller configuration settings. options: category: required: true description: - Category to execute on OOB controller type: str command: required: true description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - User for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str bios_attribute_name: required: false description: - name of BIOS attribute to update default: 'null' type: str version_added: "2.8" bios_attribute_value: required: false description: - value of BIOS attribute to update default: 'null' type: str version_added: "2.8" timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: "2.8" author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Set BootMode to UEFI redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: BootMode bios_attribute_value: Uefi baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set BootMode to Legacy BIOS redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: BootMode bios_attribute_value: Bios baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Enable PXE Boot for NIC1 redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: PxeDev1EnDis bios_attribute_value: Enabled baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set BIOS default settings with a timeout of 20 seconds redfish_config: category: Systems command: SetBiosDefaultSettings baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native # More will be added as module features are expanded CATEGORY_COMMANDS_ALL = { "Systems": ["SetBiosDefaultSettings", "SetBiosAttributes"] } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), bios_attribute_name=dict(default='null'), bios_attribute_value=dict(default='null'), timeout=dict(type='int', default=10) ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # BIOS attributes to update bios_attributes = {'bios_attr_name': module.params['bios_attribute_name'], 'bios_attr_value': module.params['bios_attribute_value']} # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetBiosDefaultSettings": result = rf_utils.set_bios_default_settings() elif command == "SetBiosAttributes": result = rf_utils.set_bios_attributes(bios_attributes) # Return data back or fail with proper message if result['ret'] is True: module.exit_json(changed=result['changed'], msg=to_native(result['msg'])) else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
62,937
redfish_command - Accounts - UpdateUserName / UpdatePasswordPolicy
#### SUMMARY This feature would implement a UpdateUserName command for the Accounts category of redfish_command, to update user name. And also implement a UpdatePasswordPolicy command for the Accounts category of redfish_command to change password policy. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME redfish_command ##### ADDITIONAL INFORMATION These 2 commands would help user to update user name or update password policy
https://github.com/ansible/ansible/issues/62937
https://github.com/ansible/ansible/pull/62941
92a39a0910e6783efb36b87aa108a24db1481285
31f3a29613d47908939e863d953a55c9dc7bada1
2019-09-29T03:22:15Z
python
2019-10-29T13:13:40Z
lib/ansible/module_utils/redfish_utils.py
# Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import json from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import http_client from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} class RedfishUtils(object): def __init__(self, creds, root_uri, timeout, module): self.root_uri = root_uri self.creds = creds self.timeout = timeout self.module = module self.service_root = '/redfish/v1/' self._init_session() # The following functions are to send GET/POST/PATCH/DELETE requests def get_request(self, uri): try: resp = open_url(uri, method="GET", headers=GET_HEADERS, url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) data = json.loads(resp.read()) headers = dict((k.lower(), v) for (k, v) in resp.info().items()) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'data': data, 'headers': headers} def post_request(self, uri, pyld): try: resp = open_url(uri, data=json.dumps(pyld), headers=POST_HEADERS, method="POST", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def patch_request(self, uri, pyld): headers = PATCH_HEADERS r = self.get_request(uri) if r['ret']: # Get etag from etag header or @odata.etag property etag = r['headers'].get('etag') if not etag: etag = r['data'].get('@odata.etag') if etag: # Make copy of headers and add If-Match header headers = dict(headers) headers['If-Match'] = etag try: resp = open_url(uri, data=json.dumps(pyld), headers=headers, method="PATCH", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def delete_request(self, uri, pyld=None): try: data = json.dumps(pyld) if pyld else None resp = open_url(uri, data=data, headers=DELETE_HEADERS, method="DELETE", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} @staticmethod def _get_extended_message(error): """ Get Redfish ExtendedInfo message from response payload if present :param error: an HTTPError exception :type error: HTTPError :return: the ExtendedInfo message if present, else standard HTTP error """ msg = http_client.responses.get(error.code, '') if error.code >= 400: try: body = error.read().decode('utf-8') data = json.loads(body) ext_info = data['error']['@Message.ExtendedInfo'] msg = ext_info[0]['Message'] except Exception: pass return msg def _init_session(self): pass def _find_accountservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} else: account_service = data["AccountService"]["@odata.id"] response = self.get_request(self.root_uri + account_service) if response['ret'] is False: return response data = response['data'] accounts = data['Accounts']['@odata.id'] if accounts[-1:] == '/': accounts = accounts[:-1] self.accounts_uri = accounts return {'ret': True} def _find_sessionservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'SessionService' not in data: return {'ret': False, 'msg': "SessionService resource not found"} else: session_service = data["SessionService"]["@odata.id"] response = self.get_request(self.root_uri + session_service) if response['ret'] is False: return response data = response['data'] sessions = data['Sessions']['@odata.id'] if sessions[-1:] == '/': sessions = sessions[:-1] self.sessions_uri = sessions return {'ret': True} def _find_systems_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Systems' not in data: return {'ret': False, 'msg': "Systems resource not found"} response = self.get_request(self.root_uri + data['Systems']['@odata.id']) if response['ret'] is False: return response self.systems_uris = [ i['@odata.id'] for i in response['data'].get('Members', [])] if not self.systems_uris: return { 'ret': False, 'msg': "ComputerSystem's Members array is either empty or missing"} return {'ret': True} def _find_updateservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'UpdateService' not in data: return {'ret': False, 'msg': "UpdateService resource not found"} else: update = data["UpdateService"]["@odata.id"] self.update_uri = update response = self.get_request(self.root_uri + update) if response['ret'] is False: return response data = response['data'] firmware_inventory = data['FirmwareInventory'][u'@odata.id'] self.firmware_uri = firmware_inventory return {'ret': True} def _find_chassis_resource(self): chassis_service = [] response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Chassis' not in data: return {'ret': False, 'msg': "Chassis resource not found"} else: chassis = data["Chassis"]["@odata.id"] response = self.get_request(self.root_uri + chassis) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: chassis_service.append(member[u'@odata.id']) self.chassis_uri_list = chassis_service return {'ret': True} def _find_managers_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Managers' not in data: return {'ret': False, 'msg': "Manager resource not found"} else: manager = data["Managers"]["@odata.id"] response = self.get_request(self.root_uri + manager) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: manager_service = member[u'@odata.id'] self.manager_uri = manager_service return {'ret': True} def get_logs(self): log_svcs_uri_list = [] list_of_logs = [] properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat', 'Message', 'MessageId', 'MessageArgs'] # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data.get('Members', []): response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id']) if response['ret'] is False: return response _data = response['data'] if 'Entries' in _data: log_svcs_uri_list.append(_data['Entries'][u'@odata.id']) # For each entry in LogServices, get log name and all log entries for log_svcs_uri in log_svcs_uri_list: logs = {} list_of_log_entries = [] response = self.get_request(self.root_uri + log_svcs_uri) if response['ret'] is False: return response data = response['data'] logs['Description'] = data.get('Description', 'Collection of log entries') # Get all log entries for each type of log found for logEntry in data.get('Members', []): entry = {} for prop in properties: if prop in logEntry: entry[prop] = logEntry.get(prop) if entry: list_of_log_entries.append(entry) log_name = log_svcs_uri.split('/')[-1] logs[log_name] = list_of_log_entries list_of_logs.append(logs) # list_of_logs[logs{list_of_log_entries[entry{}]}] return {'ret': True, 'entries': list_of_logs} def clear_logs(self): # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data[u'Members']: response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"]) if response['ret'] is False: return response _data = response['data'] # Check to make sure option is available, otherwise error is ugly if "Actions" in _data: if "#LogService.ClearLog" in _data[u"Actions"]: self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {}) if response['ret'] is False: return response return {'ret': True} def aggregate(self, func): ret = True entries = [] for systems_uri in self.systems_uris: inventory = func(systems_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'systems_uri': systems_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_storage_controller_inventory(self, systems_uri): result = {} controller_list = [] controller_results = [] # Get these entries, but does not fail if not found properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers', 'Location', 'Manufacturer', 'Model', 'Name', 'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status'] key = "StorageControllers" # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'Storage' not in data: return {'ret': False, 'msg': "Storage resource not found"} # Get a list of all storage controllers and build respective URIs storage_uri = data['Storage']["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Loop through Members and their StorageControllers # and gather properties from each StorageController if data[u'Members']: for storage_member in data[u'Members']: storage_member_uri = storage_member[u'@odata.id'] response = self.get_request(self.root_uri + storage_member_uri) data = response['data'] if key in data: controller_list = data[key] for controller in controller_list: controller_result = {} for property in properties: if property in controller: controller_result[property] = controller[property] controller_results.append(controller_result) result['entries'] = controller_results return result else: return {'ret': False, 'msg': "Storage resource not found"} def get_multi_storage_controller_inventory(self): return self.aggregate(self.get_storage_controller_inventory) def get_disk_inventory(self, systems_uri): result = {'entries': []} controller_list = [] # Get these entries, but does not fail if not found properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes', 'EncryptionAbility', 'EncryptionStatus', 'FailurePredicted', 'HotspareType', 'Id', 'Identifiers', 'Manufacturer', 'MediaType', 'Model', 'Name', 'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision', 'RotationSpeedRPM', 'SerialNumber', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data[u'Members']: for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] if 'Drives' in data: for device in data[u'Drives']: disk_uri = self.root_uri + device[u'@odata.id'] response = self.get_request(disk_uri) data = response['data'] drive_result = {} for property in properties: if property in data: if data[property] is not None: drive_result[property] = data[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) if 'SimpleStorage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data["SimpleStorage"]["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Name' in data: controller_name = data['Name'] else: sc_id = data.get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] for device in data[u'Devices']: drive_result = {} for property in properties: if property in device: drive_result[property] = device[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) return result def get_multi_disk_inventory(self): return self.aggregate(self.get_disk_inventory) def get_volume_inventory(self, systems_uri): result = {'entries': []} controller_list = [] volume_list = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes', 'Capacity', 'CapacityBytes', 'CapacitySources', 'Encrypted', 'EncryptionTypes', 'Identifiers', 'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities', 'AllocatedPools', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data.get('Members'): for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id volume_results = [] if 'Volumes' in data: # Get a list of all volumes and build respective URIs volumes_uri = data[u'Volumes'][u'@odata.id'] response = self.get_request(self.root_uri + volumes_uri) data = response['data'] if data.get('Members'): for volume in data[u'Members']: volume_list.append(volume[u'@odata.id']) for v in volume_list: uri = self.root_uri + v response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] volume_result = {} for property in properties: if property in data: if data[property] is not None: volume_result[property] = data[property] # Get related Drives Id drive_id_list = [] if 'Links' in data: if 'Drives' in data[u'Links']: for link in data[u'Links'][u'Drives']: drive_id_link = link[u'@odata.id'] drive_id = drive_id_link.split("/")[-1] drive_id_list.append({'Id': drive_id}) volume_result['Linked_drives'] = drive_id_list volume_results.append(volume_result) volumes = {'Controller': controller_name, 'Volumes': volume_results} result["entries"].append(volumes) else: return {'ret': False, 'msg': "Storage resource not found"} return result def get_multi_volume_inventory(self): return self.aggregate(self.get_volume_inventory) def restart_manager_gracefully(self): result = {} key = "Actions" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] action_uri = data[key]["#Manager.Reset"]["target"] payload = {'ResetType': 'GracefulRestart'} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True} def manage_indicator_led(self, command): result = {} key = 'IndicatorLED' payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'} result = {} for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} if command in payloads.keys(): payload = {'IndicatorLED': payloads[command]} response = self.patch_request(self.root_uri + chassis_uri, payload) if response['ret'] is False: return response else: return {'ret': False, 'msg': 'Invalid command'} return result def _map_reset_type(self, reset_type, allowable_values): equiv_types = { 'On': 'ForceOn', 'ForceOn': 'On', 'ForceOff': 'GracefulShutdown', 'GracefulShutdown': 'ForceOff', 'GracefulRestart': 'ForceRestart', 'ForceRestart': 'GracefulRestart' } if reset_type in allowable_values: return reset_type if reset_type not in equiv_types: return reset_type mapped_type = equiv_types[reset_type] if mapped_type in allowable_values: return mapped_type return reset_type def manage_system_power(self, command): key = "Actions" reset_type_values = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] # command should be PowerOn, PowerForceOff, etc. if not command.startswith('Power'): return {'ret': False, 'msg': 'Invalid Command (%s)' % command} reset_type = command[5:] # map Reboot to a ResetType that does a reboot if reset_type == 'Reboot': reset_type = 'GracefulRestart' if reset_type not in reset_type_values: return {'ret': False, 'msg': 'Invalid Command (%s)' % command} # read the system resource and get the current power state response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response data = response['data'] power_state = data.get('PowerState') # if power is already in target state, nothing to do if power_state == "On" and reset_type in ['On', 'ForceOn']: return {'ret': True, 'changed': False} if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']: return {'ret': True, 'changed': False} # get the #ComputerSystem.Reset Action and target URI if key not in data or '#ComputerSystem.Reset' not in data[key]: return {'ret': False, 'msg': 'Action #ComputerSystem.Reset not found'} reset_action = data[key]['#ComputerSystem.Reset'] if 'target' not in reset_action: return {'ret': False, 'msg': 'target URI missing from Action #ComputerSystem.Reset'} action_uri = reset_action['target'] # get AllowableValues from ActionInfo allowable_values = None if '@Redfish.ActionInfo' in reset_action: action_info_uri = reset_action.get('@Redfish.ActionInfo') response = self.get_request(self.root_uri + action_info_uri) if response['ret'] is True: data = response['data'] if 'Parameters' in data: params = data['Parameters'] for param in params: if param.get('Name') == 'ResetType': allowable_values = param.get('AllowableValues') break # fallback to @Redfish.AllowableValues annotation if allowable_values is None: allowable_values = reset_action.get('[email protected]', []) # map ResetType to an allowable value if needed if reset_type not in allowable_values: reset_type = self._map_reset_type(reset_type, allowable_values) # define payload payload = {'ResetType': reset_type} # POST to Action URI response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def _find_account_uri(self, username=None, acct_id=None): if not any((username, acct_id)): return {'ret': False, 'msg': 'Must provide either account_id or account_username'} response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if username: if username == data.get('UserName'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} if acct_id: if acct_id == data.get('Id'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No account with the given account_id or account_username found'} def _find_empty_account_slot(self): response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] if uris: # first slot may be reserved, so move to end of list uris += [uris.pop(0)] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if data.get('UserName') == "" and not data.get('Enabled', True): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No empty account slot found'} def list_users(self): result = {} # listing all users has always been slower than other operations, why? user_list = [] users_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled'] response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for users in data.get('Members', []): user_list.append(users[u'@odata.id']) # user_list[] are URIs # for each user, get details for uri in user_list: user = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: user[property] = data[property] users_results.append(user) result["entries"] = users_results return result def add_user_via_patch(self, user): if user.get('account_id'): # If Id slot specified, use it response = self._find_account_uri(acct_id=user.get('account_id')) else: # Otherwise find first empty slot response = self._find_empty_account_slot() if not response['ret']: return response uri = response['uri'] payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def add_user(self, user): if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_account_uri(username=user.get('account_username')) if response['ret']: # account_username already exists, nothing to do return {'ret': True, 'changed': False} response = self.get_request(self.root_uri + self.accounts_uri) if not response['ret']: return response headers = response['headers'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'POST' not in methods: # if Allow header present and POST not listed, add via PATCH return self.add_user_via_patch(user) payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.post_request(self.root_uri + self.accounts_uri, payload) if not response['ret']: if response.get('status') == 405: # if POST returned a 405, try to add via PATCH return self.add_user_via_patch(user) else: return response return {'ret': True} def enable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('Enabled'): # account already enabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': True} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user_via_patch(self, user, uri=None, data=None): if not uri: response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data and data.get('UserName') == '' and not data.get('Enabled', False): # account UserName already cleared, nothing to do return {'ret': True, 'changed': False} payload = {'UserName': ''} if 'Enabled' in data: payload['Enabled'] = False response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: if response.get('no_match'): # account does not exist, nothing to do return {'ret': True, 'changed': False} else: # some error encountered return response uri = response['uri'] headers = response['headers'] data = response['data'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'DELETE' not in methods: # if Allow header present and DELETE not listed, del via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) response = self.delete_request(self.root_uri + uri) if not response['ret']: if response.get('status') == 405: # if DELETE returned a 405, try to delete via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) else: return response return {'ret': True} def disable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if not data.get('Enabled'): # account already disabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': False} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_role(self, user): if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('RoleId') == user.get('account_roleid'): # account already has RoleId , nothing to do return {'ret': True, 'changed': False} payload = {'RoleId': user.get('account_roleid')} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_password(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'Password': user['account_password']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def get_sessions(self): result = {} # listing all users has always been slower than other operations, why? session_list = [] sessions_results = [] # Get these entries, but does not fail if not found properties = ['Description', 'Id', 'Name', 'UserName'] response = self.get_request(self.root_uri + self.sessions_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for sessions in data[u'Members']: session_list.append(sessions[u'@odata.id']) # session_list[] are URIs # for each session, get details for uri in session_list: session = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: session[property] = data[property] sessions_results.append(session) result["entries"] = sessions_results return result def get_firmware_update_capabilities(self): result = {} response = self.get_request(self.root_uri + self.update_uri) if response['ret'] is False: return response result['ret'] = True result['entries'] = {} data = response['data'] if "Actions" in data: actions = data['Actions'] if len(actions) > 0: for key in actions.keys(): action = actions.get(key) if 'title' in action: title = action['title'] else: title = key result['entries'][title] = action.get('[email protected]', ["Key [email protected] not found"]) else: return {'ret': "False", 'msg': "Actions list is empty."} else: return {'ret': "False", 'msg': "Key Actions not found."} return result def get_firmware_inventory(self): result = {} response = self.get_request(self.root_uri + self.firmware_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] result['entries'] = [] for device in data[u'Members']: uri = self.root_uri + device[u'@odata.id'] # Get details for each device response = self.get_request(uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] firmware = {} # Get these standard properties if present for key in ['Name', 'Id', 'Status', 'Version', 'Updateable', 'SoftwareId', 'LowestSupportedVersion', 'Manufacturer', 'ReleaseDate']: if key in data: firmware[key] = data.get(key) result['entries'].append(firmware) return result def get_bios_attributes(self, systems_uri): result = {} bios_attributes = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for attribute in data[u'Attributes'].items(): bios_attributes[attribute[0]] = attribute[1] result["entries"] = bios_attributes return result def get_multi_bios_attributes(self): return self.aggregate(self.get_bios_attributes) def _get_boot_options_dict(self, boot): # Get these entries from BootOption, if present properties = ['DisplayName', 'BootOptionReference'] # Retrieve BootOptions if present if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']: boot_options_uri = boot['BootOptions']["@odata.id"] # Get BootOptions resource response = self.get_request(self.root_uri + boot_options_uri) if response['ret'] is False: return {} data = response['data'] # Retrieve Members array if 'Members' not in data: return {} members = data['Members'] else: members = [] # Build dict of BootOptions keyed by BootOptionReference boot_options_dict = {} for member in members: if '@odata.id' not in member: return {} boot_option_uri = member['@odata.id'] response = self.get_request(self.root_uri + boot_option_uri) if response['ret'] is False: return {} data = response['data'] if 'BootOptionReference' not in data: return {} boot_option_ref = data['BootOptionReference'] # fetch the props to display for this boot device boot_props = {} for prop in properties: if prop in data: boot_props[prop] = data[prop] boot_options_dict[boot_option_ref] = boot_props return boot_options_dict def get_boot_order(self, systems_uri): result = {} # Retrieve System resource response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # Build boot device list boot_device_list = [] for ref in boot_order: boot_device_list.append( boot_options_dict.get(ref, {'BootOptionReference': ref})) result["entries"] = boot_device_list return result def get_multi_boot_order(self): return self.aggregate(self.get_boot_order) def get_boot_override(self, systems_uri): result = {} properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget", "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "[email protected]"] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Boot' not in data: return {'ret': False, 'msg': "Key Boot not found"} boot = data['Boot'] boot_overrides = {} if "BootSourceOverrideEnabled" in boot: if boot["BootSourceOverrideEnabled"] is not False: for property in properties: if property in boot: if boot[property] is not None: boot_overrides[property] = boot[property] else: return {'ret': False, 'msg': "No boot override is enabled."} result['entries'] = boot_overrides return result def get_multi_boot_override(self): return self.aggregate(self.get_boot_override) def set_bios_default_settings(self): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] reset_bios_settings_uri = data["Actions"]["#Bios.ResetBios"]["target"] response = self.post_request(self.root_uri + reset_bios_settings_uri, {}) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Set BIOS to default settings"} def set_one_time_boot_device(self, bootdevice, uefi_target, boot_next): result = {} key = "Boot" if not bootdevice: return {'ret': False, 'msg': "bootdevice option required for SetOneTimeBoot"} # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} boot = data[key] annotation = '[email protected]' if annotation in boot: allowable_values = boot[annotation] if isinstance(allowable_values, list) and bootdevice not in allowable_values: return {'ret': False, 'msg': "Boot device %s not in list of allowable values (%s)" % (bootdevice, allowable_values)} # read existing values enabled = boot.get('BootSourceOverrideEnabled') target = boot.get('BootSourceOverrideTarget') cur_uefi_target = boot.get('UefiTargetBootSourceOverride') cur_boot_next = boot.get('BootNext') if bootdevice == 'UefiTarget': if not uefi_target: return {'ret': False, 'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"} if enabled == 'Once' and target == bootdevice and uefi_target == cur_uefi_target: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'UefiTargetBootSourceOverride': uefi_target } } elif bootdevice == 'UefiBootNext': if not boot_next: return {'ret': False, 'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"} if enabled == 'Once' and target == bootdevice and boot_next == cur_boot_next: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'BootNext': boot_next } } else: if enabled == 'Once' and target == bootdevice: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice } } response = self.patch_request(self.root_uri + self.systems_uris[0], payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def set_bios_attributes(self, attr): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # First, check if BIOS attribute exists if attr['bios_attr_name'] not in data[u'Attributes']: return {'ret': False, 'msg': "BIOS attribute not found"} # Find out if value is already set to what we want. If yes, return if data[u'Attributes'][attr['bios_attr_name']] == attr['bios_attr_value']: return {'ret': True, 'changed': False, 'msg': "BIOS attribute already set"} set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"]["@odata.id"] # Example: bios_attr = {\"name\":\"value\"} bios_attr = "{\"" + attr['bios_attr_name'] + "\":\"" + attr['bios_attr_value'] + "\"}" payload = {"Attributes": json.loads(bios_attr)} response = self.patch_request(self.root_uri + set_bios_attr_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified BIOS attribute"} def set_boot_order(self, boot_list): if not boot_list: return {'ret': False, 'msg': "boot_order list required for SetBootOrder command"} # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # validate boot_list against BootOptionReferences if available if boot_options_dict: boot_option_references = boot_options_dict.keys() for ref in boot_list: if ref not in boot_option_references: return {'ret': False, 'msg': "BootOptionReference %s not found in BootOptions" % ref} # If requested BootOrder is already set, nothing to do if boot_order == boot_list: return {'ret': True, 'changed': False, 'msg': "BootOrder already set to %s" % boot_list} payload = { 'Boot': { 'BootOrder': boot_list } } response = self.patch_request(self.root_uri + systems_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set"} def set_default_boot_order(self): # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # get the #ComputerSystem.SetDefaultBootOrder Action and target URI action = '#ComputerSystem.SetDefaultBootOrder' if 'Actions' not in data or action not in data['Actions']: return {'ret': False, 'msg': 'Action %s not found' % action} if 'target' not in data['Actions'][action]: return {'ret': False, 'msg': 'target URI missing from Action %s' % action} action_uri = data['Actions'][action]['target'] # POST to Action URI payload = {} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set to default"} def get_chassis_inventory(self): result = {} chassis_results = [] # Get these entries, but does not fail if not found properties = ['ChassisType', 'PartNumber', 'AssetTag', 'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] chassis_result = {} for property in properties: if property in data: chassis_result[property] = data[property] chassis_results.append(chassis_result) result["entries"] = chassis_results return result def get_fan_inventory(self): result = {} fan_results = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['FanName', 'Reading', 'ReadingUnits', 'Status'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: # match: found an entry for "Thermal" information = fans thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for device in data[u'Fans']: fan = {} for property in properties: if property in device: fan[property] = device[property] fan_results.append(fan) result["entries"] = fan_results return result def get_chassis_power(self): result = {} key = "Power" # Get these entries, but does not fail if not found properties = ['Name', 'PowerAllocatedWatts', 'PowerAvailableWatts', 'PowerCapacityWatts', 'PowerConsumedWatts', 'PowerMetrics', 'PowerRequestedWatts', 'RelatedItem', 'Status'] chassis_power_results = [] # Go through list for chassis_uri in self.chassis_uri_list: chassis_power_result = {} response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: response = self.get_request(self.root_uri + data[key]['@odata.id']) data = response['data'] if 'PowerControl' in data: if len(data['PowerControl']) > 0: data = data['PowerControl'][0] for property in properties: if property in data: chassis_power_result[property] = data[property] else: return {'ret': False, 'msg': 'Key PowerControl not found.'} chassis_power_results.append(chassis_power_result) else: return {'ret': False, 'msg': 'Key Power not found.'} result['entries'] = chassis_power_results return result def get_chassis_thermals(self): result = {} sensors = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical', 'UpperThresholdFatal', 'UpperThresholdNonCritical', 'LowerThresholdCritical', 'LowerThresholdFatal', 'LowerThresholdNonCritical', 'MaxReadingRangeTemp', 'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem', 'SensorNumber'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if "Temperatures" in data: for sensor in data[u'Temperatures']: sensor_result = {} for property in properties: if property in sensor: if sensor[property] is not None: sensor_result[property] = sensor[property] sensors.append(sensor_result) if sensors is None: return {'ret': False, 'msg': 'Key Temperatures was not found.'} result['entries'] = sensors return result def get_cpu_inventory(self, systems_uri): result = {} cpu_list = [] cpu_results = [] key = "Processors" # Get these entries, but does not fail if not found properties = ['Id', 'Manufacturer', 'Model', 'MaxSpeedMHz', 'TotalCores', 'TotalThreads', 'Status'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} processors_uri = data[key]["@odata.id"] # Get a list of all CPUs and build respective URIs response = self.get_request(self.root_uri + processors_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for cpu in data[u'Members']: cpu_list.append(cpu[u'@odata.id']) for c in cpu_list: cpu = {} uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: cpu[property] = data[property] cpu_results.append(cpu) result["entries"] = cpu_results return result def get_multi_cpu_inventory(self): return self.aggregate(self.get_cpu_inventory) def get_memory_inventory(self, systems_uri): result = {} memory_list = [] memory_results = [] key = "Memory" # Get these entries, but does not fail if not found properties = ['SerialNumber', 'MemoryDeviceType', 'PartNuber', 'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} memory_uri = data[key]["@odata.id"] # Get a list of all DIMMs and build respective URIs response = self.get_request(self.root_uri + memory_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for dimm in data[u'Members']: memory_list.append(dimm[u'@odata.id']) for m in memory_list: dimm = {} uri = self.root_uri + m response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if "Status" in data: if "State" in data["Status"]: if data["Status"]["State"] == "Absent": continue else: continue for property in properties: if property in data: dimm[property] = data[property] memory_results.append(dimm) result["entries"] = memory_results return result def get_multi_memory_inventory(self): return self.aggregate(self.get_memory_inventory) def get_nic_inventory(self, resource_uri): result = {} nic_list = [] nic_results = [] key = "EthernetInterfaces" # Get these entries, but does not fail if not found properties = ['Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses', 'NameServers', 'MACAddress', 'PermanentMACAddress', 'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} ethernetinterfaces_uri = data[key]["@odata.id"] # Get a list of all network controllers and build respective URIs response = self.get_request(self.root_uri + ethernetinterfaces_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for nic in data[u'Members']: nic_list.append(nic[u'@odata.id']) for n in nic_list: nic = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: nic[property] = data[property] nic_results.append(nic) result["entries"] = nic_results return result def get_multi_nic_inventory(self, resource_type): ret = True entries = [] # Given resource_type, use the proper URI if resource_type == 'Systems': resource_uris = self.systems_uris elif resource_type == 'Manager': # put in a list to match what we're doing with systems_uris resource_uris = [self.manager_uri] for resource_uri in resource_uris: inventory = self.get_nic_inventory(resource_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'resource_uri': resource_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_virtualmedia(self, resource_uri): result = {} virtualmedia_list = [] virtualmedia_results = [] key = "VirtualMedia" # Get these entries, but does not fail if not found properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes', 'Image', 'ImageName', 'Name', 'WriteProtected', 'TransferMethod', 'TransferProtocolType'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} virtualmedia_uri = data[key]["@odata.id"] # Get a list of all virtual media and build respective URIs response = self.get_request(self.root_uri + virtualmedia_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for virtualmedia in data[u'Members']: virtualmedia_list.append(virtualmedia[u'@odata.id']) for n in virtualmedia_list: virtualmedia = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: virtualmedia[property] = data[property] virtualmedia_results.append(virtualmedia) result["entries"] = virtualmedia_results return result def get_multi_virtualmedia(self): ret = True entries = [] # Because _find_managers_resource() only find last Manager uri in self.manager_uri, not one list. This should be 1 issue. # I have to put manager_uri into list to reduce future changes when the issue is fixed. resource_uris = [self.manager_uri] for resource_uri in resource_uris: virtualmedia = self.get_virtualmedia(resource_uri) ret = virtualmedia.pop('ret') and ret if 'entries' in virtualmedia: entries.append(({'resource_uri': resource_uri}, virtualmedia['entries'])) return dict(ret=ret, entries=entries) def get_psu_inventory(self): result = {} psu_list = [] psu_results = [] key = "PowerSupplies" # Get these entries, but does not fail if not found properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status'] # Get a list of all Chassis and build URIs, then get all PowerSupplies # from each Power entry in the Chassis chassis_uri_list = self.chassis_uri_list for chassis_uri in chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Power' in data: power_uri = data[u'Power'][u'@odata.id'] else: continue response = self.get_request(self.root_uri + power_uri) data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} psu_list = data[key] for psu in psu_list: psu_not_present = False psu_data = {} for property in properties: if property in psu: if psu[property] is not None: if property == 'Status': if 'State' in psu[property]: if psu[property]['State'] == 'Absent': psu_not_present = True psu_data[property] = psu[property] if psu_not_present: continue psu_results.append(psu_data) result["entries"] = psu_results if not result["entries"]: return {'ret': False, 'msg': "No PowerSupply objects found"} return result def get_multi_psu_inventory(self): return self.aggregate(self.get_psu_inventory) def get_system_inventory(self, systems_uri): result = {} inventory = {} # Get these entries, but does not fail if not found properties = ['Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag', 'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary', 'ProcessorSummary', 'TrustedModules'] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for property in properties: if property in data: inventory[property] = data[property] result["entries"] = inventory return result def get_multi_system_inventory(self): return self.aggregate(self.get_system_inventory)
closed
ansible/ansible
https://github.com/ansible/ansible
62,937
redfish_command - Accounts - UpdateUserName / UpdatePasswordPolicy
#### SUMMARY This feature would implement a UpdateUserName command for the Accounts category of redfish_command, to update user name. And also implement a UpdatePasswordPolicy command for the Accounts category of redfish_command to change password policy. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME redfish_command ##### ADDITIONAL INFORMATION These 2 commands would help user to update user name or update password policy
https://github.com/ansible/ansible/issues/62937
https://github.com/ansible/ansible/pull/62941
92a39a0910e6783efb36b87aa108a24db1481285
31f3a29613d47908939e863d953a55c9dc7bada1
2019-09-29T03:22:15Z
python
2019-10-29T13:13:40Z
lib/ansible/modules/remote_management/redfish/redfish_command.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_command version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to perform an action. - Manages OOB controller ex. reboot, log management. - Manages OOB controller users ex. add, remove, update. - Manages system power ex. on, off, graceful and forced reboot. options: category: required: true description: - Category to execute on OOB controller type: str command: required: true description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - Username for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str id: required: false aliases: [ account_id ] description: - ID of account to delete/modify type: str version_added: "2.8" new_username: required: false aliases: [ account_username ] description: - Username of account to add/delete/modify type: str version_added: "2.8" new_password: required: false aliases: [ account_password ] description: - New password of account to add/modify type: str version_added: "2.8" roleid: required: false aliases: [ account_roleid ] description: - Role of account to add/modify type: str version_added: "2.8" bootdevice: required: false description: - bootdevice when setting boot configuration type: str timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: '2.8' uefi_target: required: false description: - UEFI target when bootdevice is "UefiTarget" type: str version_added: "2.9" boot_next: required: false description: - BootNext target when bootdevice is "UefiBootNext" type: str version_added: "2.9" author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Restart system power gracefully redfish_command: category: Systems command: PowerGracefulRestart baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set one-time boot device to {{ bootdevice }} redfish_command: category: Systems command: SetOneTimeBoot bootdevice: "{{ bootdevice }}" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set one-time boot device to UefiTarget of "/0x31/0x33/0x01/0x01" redfish_command: category: Systems command: SetOneTimeBoot bootdevice: "UefiTarget" uefi_target: "/0x31/0x33/0x01/0x01" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set one-time boot device to BootNext target of "Boot0001" redfish_command: category: Systems command: SetOneTimeBoot bootdevice: "UefiBootNext" boot_next: "Boot0001" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set chassis indicator LED to blink redfish_command: category: Chassis command: IndicatorLedBlink baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Add user redfish_command: category: Accounts command: AddUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" new_username: "{{ new_username }}" new_password: "{{ new_password }}" roleid: "{{ roleid }}" - name: Add user using new option aliases redfish_command: category: Accounts command: AddUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" account_password: "{{ account_password }}" account_roleid: "{{ account_roleid }}" - name: Delete user redfish_command: category: Accounts command: DeleteUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" - name: Disable user redfish_command: category: Accounts command: DisableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" - name: Enable user redfish_command: category: Accounts command: EnableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" - name: Add and enable user redfish_command: category: Accounts command: AddUser,EnableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" new_username: "{{ new_username }}" new_password: "{{ new_password }}" roleid: "{{ roleid }}" - name: Update user password redfish_command: category: Accounts command: UpdateUserPassword baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" account_password: "{{ account_password }}" - name: Update user role redfish_command: category: Accounts command: UpdateUserRole baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" roleid: "{{ roleid }}" - name: Clear Manager Logs with a timeout of 20 seconds redfish_command: category: Manager command: ClearLogs baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native # More will be added as module features are expanded CATEGORY_COMMANDS_ALL = { "Systems": ["PowerOn", "PowerForceOff", "PowerForceRestart", "PowerGracefulRestart", "PowerGracefulShutdown", "PowerReboot", "SetOneTimeBoot"], "Chassis": ["IndicatorLedOn", "IndicatorLedOff", "IndicatorLedBlink"], "Accounts": ["AddUser", "EnableUser", "DeleteUser", "DisableUser", "UpdateUserRole", "UpdateUserPassword"], "Manager": ["GracefulRestart", "ClearLogs"], } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), id=dict(aliases=["account_id"]), new_username=dict(aliases=["account_username"]), new_password=dict(aliases=["account_password"], no_log=True), roleid=dict(aliases=["account_roleid"]), bootdevice=dict(), timeout=dict(type='int', default=10), uefi_target=dict(), boot_next=dict() ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # user to add/modify/delete user = {'account_id': module.params['id'], 'account_username': module.params['new_username'], 'account_password': module.params['new_password'], 'account_roleid': module.params['roleid']} # timeout timeout = module.params['timeout'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Accounts": ACCOUNTS_COMMANDS = { "AddUser": rf_utils.add_user, "EnableUser": rf_utils.enable_user, "DeleteUser": rf_utils.delete_user, "DisableUser": rf_utils.disable_user, "UpdateUserRole": rf_utils.update_user_role, "UpdateUserPassword": rf_utils.update_user_password } # execute only if we find an Account service resource result = rf_utils._find_accountservice_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: result = ACCOUNTS_COMMANDS[command](user) elif category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if "Power" in command: result = rf_utils.manage_system_power(command) elif command == "SetOneTimeBoot": result = rf_utils.set_one_time_boot_device( module.params['bootdevice'], module.params['uefi_target'], module.params['boot_next']) elif category == "Chassis": result = rf_utils._find_chassis_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) led_commands = ["IndicatorLedOn", "IndicatorLedOff", "IndicatorLedBlink"] # Check if more than one led_command is present num_led_commands = sum([command in led_commands for command in command_list]) if num_led_commands > 1: result = {'ret': False, 'msg': "Only one IndicatorLed command should be sent at a time."} else: for command in command_list: if command in led_commands: result = rf_utils.manage_indicator_led(command) elif category == "Manager": MANAGER_COMMANDS = { "GracefulRestart": rf_utils.restart_manager_gracefully, "ClearLogs": rf_utils.clear_logs } # execute only if we find a Manager service resource result = rf_utils._find_managers_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: result = MANAGER_COMMANDS[command]() # Return data back or fail with proper message if result['ret'] is True: del result['ret'] changed = result.get('changed', True) module.exit_json(changed=changed, msg='Action was successful') else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
59,793
Add GetSoftwareInventory command
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> During the 2019 APTS Plugfest, it was noted that the `GetFirmwareInventory` command was gathering the `FirmwareInventory` from the `UpdateService`, but not the `SoftwareInventory`. There are two options to address this request: 1. Update the `GetFirmwareInventory` command to also gather the `SoftwareInventory`. 2. Add a new `GetSoftwareInventory` command. I'll get input on these two options. [Per Tools Task Force call, agreed on option 2.] ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_facts.py redfish_utils.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Operators want to be able to get `SoftwareInventory` as well as `FirmwareInventory`. There is currently no way the gather the `SoftwareInventory` using the Ansible Redfish modules. <!--- Paste example playbooks or commands between quotes below --> **Option 1:** ```yaml tasks: - name: Get Firmware and Software Inventory redfish_facts: category: Update command: GetFirmwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result ``` **Option 2:** ```yaml tasks: - name: Get Firmware Inventory redfish_facts: category: Update command: GetFirmwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - name: Get Software Inventory redfish_facts: category: Update command: GetSoftwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/59793
https://github.com/ansible/ansible/pull/62811
31f3a29613d47908939e863d953a55c9dc7bada1
c9a669e42c3fd90ec9d6d28c60a0f56f1bd302a8
2019-07-30T16:02:33Z
python
2019-10-29T13:15:42Z
lib/ansible/module_utils/redfish_utils.py
# Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import json from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import http_client from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} class RedfishUtils(object): def __init__(self, creds, root_uri, timeout, module): self.root_uri = root_uri self.creds = creds self.timeout = timeout self.module = module self.service_root = '/redfish/v1/' self._init_session() # The following functions are to send GET/POST/PATCH/DELETE requests def get_request(self, uri): try: resp = open_url(uri, method="GET", headers=GET_HEADERS, url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) data = json.loads(resp.read()) headers = dict((k.lower(), v) for (k, v) in resp.info().items()) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'data': data, 'headers': headers} def post_request(self, uri, pyld): try: resp = open_url(uri, data=json.dumps(pyld), headers=POST_HEADERS, method="POST", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def patch_request(self, uri, pyld): headers = PATCH_HEADERS r = self.get_request(uri) if r['ret']: # Get etag from etag header or @odata.etag property etag = r['headers'].get('etag') if not etag: etag = r['data'].get('@odata.etag') if etag: # Make copy of headers and add If-Match header headers = dict(headers) headers['If-Match'] = etag try: resp = open_url(uri, data=json.dumps(pyld), headers=headers, method="PATCH", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def delete_request(self, uri, pyld=None): try: data = json.dumps(pyld) if pyld else None resp = open_url(uri, data=data, headers=DELETE_HEADERS, method="DELETE", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} @staticmethod def _get_extended_message(error): """ Get Redfish ExtendedInfo message from response payload if present :param error: an HTTPError exception :type error: HTTPError :return: the ExtendedInfo message if present, else standard HTTP error """ msg = http_client.responses.get(error.code, '') if error.code >= 400: try: body = error.read().decode('utf-8') data = json.loads(body) ext_info = data['error']['@Message.ExtendedInfo'] msg = ext_info[0]['Message'] except Exception: pass return msg def _init_session(self): pass def _find_accountservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} else: account_service = data["AccountService"]["@odata.id"] response = self.get_request(self.root_uri + account_service) if response['ret'] is False: return response data = response['data'] accounts = data['Accounts']['@odata.id'] if accounts[-1:] == '/': accounts = accounts[:-1] self.accounts_uri = accounts return {'ret': True} def _find_sessionservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'SessionService' not in data: return {'ret': False, 'msg': "SessionService resource not found"} else: session_service = data["SessionService"]["@odata.id"] response = self.get_request(self.root_uri + session_service) if response['ret'] is False: return response data = response['data'] sessions = data['Sessions']['@odata.id'] if sessions[-1:] == '/': sessions = sessions[:-1] self.sessions_uri = sessions return {'ret': True} def _find_systems_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Systems' not in data: return {'ret': False, 'msg': "Systems resource not found"} response = self.get_request(self.root_uri + data['Systems']['@odata.id']) if response['ret'] is False: return response self.systems_uris = [ i['@odata.id'] for i in response['data'].get('Members', [])] if not self.systems_uris: return { 'ret': False, 'msg': "ComputerSystem's Members array is either empty or missing"} return {'ret': True} def _find_updateservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'UpdateService' not in data: return {'ret': False, 'msg': "UpdateService resource not found"} else: update = data["UpdateService"]["@odata.id"] self.update_uri = update response = self.get_request(self.root_uri + update) if response['ret'] is False: return response data = response['data'] firmware_inventory = data['FirmwareInventory'][u'@odata.id'] self.firmware_uri = firmware_inventory return {'ret': True} def _find_chassis_resource(self): chassis_service = [] response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Chassis' not in data: return {'ret': False, 'msg': "Chassis resource not found"} else: chassis = data["Chassis"]["@odata.id"] response = self.get_request(self.root_uri + chassis) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: chassis_service.append(member[u'@odata.id']) self.chassis_uri_list = chassis_service return {'ret': True} def _find_managers_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Managers' not in data: return {'ret': False, 'msg': "Manager resource not found"} else: manager = data["Managers"]["@odata.id"] response = self.get_request(self.root_uri + manager) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: manager_service = member[u'@odata.id'] self.manager_uri = manager_service return {'ret': True} def get_logs(self): log_svcs_uri_list = [] list_of_logs = [] properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat', 'Message', 'MessageId', 'MessageArgs'] # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data.get('Members', []): response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id']) if response['ret'] is False: return response _data = response['data'] if 'Entries' in _data: log_svcs_uri_list.append(_data['Entries'][u'@odata.id']) # For each entry in LogServices, get log name and all log entries for log_svcs_uri in log_svcs_uri_list: logs = {} list_of_log_entries = [] response = self.get_request(self.root_uri + log_svcs_uri) if response['ret'] is False: return response data = response['data'] logs['Description'] = data.get('Description', 'Collection of log entries') # Get all log entries for each type of log found for logEntry in data.get('Members', []): entry = {} for prop in properties: if prop in logEntry: entry[prop] = logEntry.get(prop) if entry: list_of_log_entries.append(entry) log_name = log_svcs_uri.split('/')[-1] logs[log_name] = list_of_log_entries list_of_logs.append(logs) # list_of_logs[logs{list_of_log_entries[entry{}]}] return {'ret': True, 'entries': list_of_logs} def clear_logs(self): # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data[u'Members']: response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"]) if response['ret'] is False: return response _data = response['data'] # Check to make sure option is available, otherwise error is ugly if "Actions" in _data: if "#LogService.ClearLog" in _data[u"Actions"]: self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {}) if response['ret'] is False: return response return {'ret': True} def aggregate(self, func): ret = True entries = [] for systems_uri in self.systems_uris: inventory = func(systems_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'systems_uri': systems_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_storage_controller_inventory(self, systems_uri): result = {} controller_list = [] controller_results = [] # Get these entries, but does not fail if not found properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers', 'Location', 'Manufacturer', 'Model', 'Name', 'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status'] key = "StorageControllers" # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'Storage' not in data: return {'ret': False, 'msg': "Storage resource not found"} # Get a list of all storage controllers and build respective URIs storage_uri = data['Storage']["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Loop through Members and their StorageControllers # and gather properties from each StorageController if data[u'Members']: for storage_member in data[u'Members']: storage_member_uri = storage_member[u'@odata.id'] response = self.get_request(self.root_uri + storage_member_uri) data = response['data'] if key in data: controller_list = data[key] for controller in controller_list: controller_result = {} for property in properties: if property in controller: controller_result[property] = controller[property] controller_results.append(controller_result) result['entries'] = controller_results return result else: return {'ret': False, 'msg': "Storage resource not found"} def get_multi_storage_controller_inventory(self): return self.aggregate(self.get_storage_controller_inventory) def get_disk_inventory(self, systems_uri): result = {'entries': []} controller_list = [] # Get these entries, but does not fail if not found properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes', 'EncryptionAbility', 'EncryptionStatus', 'FailurePredicted', 'HotspareType', 'Id', 'Identifiers', 'Manufacturer', 'MediaType', 'Model', 'Name', 'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision', 'RotationSpeedRPM', 'SerialNumber', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data[u'Members']: for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] if 'Drives' in data: for device in data[u'Drives']: disk_uri = self.root_uri + device[u'@odata.id'] response = self.get_request(disk_uri) data = response['data'] drive_result = {} for property in properties: if property in data: if data[property] is not None: drive_result[property] = data[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) if 'SimpleStorage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data["SimpleStorage"]["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Name' in data: controller_name = data['Name'] else: sc_id = data.get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] for device in data[u'Devices']: drive_result = {} for property in properties: if property in device: drive_result[property] = device[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) return result def get_multi_disk_inventory(self): return self.aggregate(self.get_disk_inventory) def get_volume_inventory(self, systems_uri): result = {'entries': []} controller_list = [] volume_list = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes', 'Capacity', 'CapacityBytes', 'CapacitySources', 'Encrypted', 'EncryptionTypes', 'Identifiers', 'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities', 'AllocatedPools', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data.get('Members'): for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id volume_results = [] if 'Volumes' in data: # Get a list of all volumes and build respective URIs volumes_uri = data[u'Volumes'][u'@odata.id'] response = self.get_request(self.root_uri + volumes_uri) data = response['data'] if data.get('Members'): for volume in data[u'Members']: volume_list.append(volume[u'@odata.id']) for v in volume_list: uri = self.root_uri + v response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] volume_result = {} for property in properties: if property in data: if data[property] is not None: volume_result[property] = data[property] # Get related Drives Id drive_id_list = [] if 'Links' in data: if 'Drives' in data[u'Links']: for link in data[u'Links'][u'Drives']: drive_id_link = link[u'@odata.id'] drive_id = drive_id_link.split("/")[-1] drive_id_list.append({'Id': drive_id}) volume_result['Linked_drives'] = drive_id_list volume_results.append(volume_result) volumes = {'Controller': controller_name, 'Volumes': volume_results} result["entries"].append(volumes) else: return {'ret': False, 'msg': "Storage resource not found"} return result def get_multi_volume_inventory(self): return self.aggregate(self.get_volume_inventory) def restart_manager_gracefully(self): result = {} key = "Actions" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] action_uri = data[key]["#Manager.Reset"]["target"] payload = {'ResetType': 'GracefulRestart'} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True} def manage_indicator_led(self, command): result = {} key = 'IndicatorLED' payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'} result = {} for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} if command in payloads.keys(): payload = {'IndicatorLED': payloads[command]} response = self.patch_request(self.root_uri + chassis_uri, payload) if response['ret'] is False: return response else: return {'ret': False, 'msg': 'Invalid command'} return result def _map_reset_type(self, reset_type, allowable_values): equiv_types = { 'On': 'ForceOn', 'ForceOn': 'On', 'ForceOff': 'GracefulShutdown', 'GracefulShutdown': 'ForceOff', 'GracefulRestart': 'ForceRestart', 'ForceRestart': 'GracefulRestart' } if reset_type in allowable_values: return reset_type if reset_type not in equiv_types: return reset_type mapped_type = equiv_types[reset_type] if mapped_type in allowable_values: return mapped_type return reset_type def manage_system_power(self, command): key = "Actions" reset_type_values = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] # command should be PowerOn, PowerForceOff, etc. if not command.startswith('Power'): return {'ret': False, 'msg': 'Invalid Command (%s)' % command} reset_type = command[5:] # map Reboot to a ResetType that does a reboot if reset_type == 'Reboot': reset_type = 'GracefulRestart' if reset_type not in reset_type_values: return {'ret': False, 'msg': 'Invalid Command (%s)' % command} # read the system resource and get the current power state response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response data = response['data'] power_state = data.get('PowerState') # if power is already in target state, nothing to do if power_state == "On" and reset_type in ['On', 'ForceOn']: return {'ret': True, 'changed': False} if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']: return {'ret': True, 'changed': False} # get the #ComputerSystem.Reset Action and target URI if key not in data or '#ComputerSystem.Reset' not in data[key]: return {'ret': False, 'msg': 'Action #ComputerSystem.Reset not found'} reset_action = data[key]['#ComputerSystem.Reset'] if 'target' not in reset_action: return {'ret': False, 'msg': 'target URI missing from Action #ComputerSystem.Reset'} action_uri = reset_action['target'] # get AllowableValues from ActionInfo allowable_values = None if '@Redfish.ActionInfo' in reset_action: action_info_uri = reset_action.get('@Redfish.ActionInfo') response = self.get_request(self.root_uri + action_info_uri) if response['ret'] is True: data = response['data'] if 'Parameters' in data: params = data['Parameters'] for param in params: if param.get('Name') == 'ResetType': allowable_values = param.get('AllowableValues') break # fallback to @Redfish.AllowableValues annotation if allowable_values is None: allowable_values = reset_action.get('[email protected]', []) # map ResetType to an allowable value if needed if reset_type not in allowable_values: reset_type = self._map_reset_type(reset_type, allowable_values) # define payload payload = {'ResetType': reset_type} # POST to Action URI response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def _find_account_uri(self, username=None, acct_id=None): if not any((username, acct_id)): return {'ret': False, 'msg': 'Must provide either account_id or account_username'} response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if username: if username == data.get('UserName'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} if acct_id: if acct_id == data.get('Id'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No account with the given account_id or account_username found'} def _find_empty_account_slot(self): response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] if uris: # first slot may be reserved, so move to end of list uris += [uris.pop(0)] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if data.get('UserName') == "" and not data.get('Enabled', True): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No empty account slot found'} def list_users(self): result = {} # listing all users has always been slower than other operations, why? user_list = [] users_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled'] response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for users in data.get('Members', []): user_list.append(users[u'@odata.id']) # user_list[] are URIs # for each user, get details for uri in user_list: user = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: user[property] = data[property] users_results.append(user) result["entries"] = users_results return result def add_user_via_patch(self, user): if user.get('account_id'): # If Id slot specified, use it response = self._find_account_uri(acct_id=user.get('account_id')) else: # Otherwise find first empty slot response = self._find_empty_account_slot() if not response['ret']: return response uri = response['uri'] payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def add_user(self, user): if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_account_uri(username=user.get('account_username')) if response['ret']: # account_username already exists, nothing to do return {'ret': True, 'changed': False} response = self.get_request(self.root_uri + self.accounts_uri) if not response['ret']: return response headers = response['headers'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'POST' not in methods: # if Allow header present and POST not listed, add via PATCH return self.add_user_via_patch(user) payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.post_request(self.root_uri + self.accounts_uri, payload) if not response['ret']: if response.get('status') == 405: # if POST returned a 405, try to add via PATCH return self.add_user_via_patch(user) else: return response return {'ret': True} def enable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('Enabled'): # account already enabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': True} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user_via_patch(self, user, uri=None, data=None): if not uri: response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data and data.get('UserName') == '' and not data.get('Enabled', False): # account UserName already cleared, nothing to do return {'ret': True, 'changed': False} payload = {'UserName': ''} if 'Enabled' in data: payload['Enabled'] = False response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: if response.get('no_match'): # account does not exist, nothing to do return {'ret': True, 'changed': False} else: # some error encountered return response uri = response['uri'] headers = response['headers'] data = response['data'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'DELETE' not in methods: # if Allow header present and DELETE not listed, del via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) response = self.delete_request(self.root_uri + uri) if not response['ret']: if response.get('status') == 405: # if DELETE returned a 405, try to delete via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) else: return response return {'ret': True} def disable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if not data.get('Enabled'): # account already disabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': False} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_role(self, user): if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('RoleId') == user.get('account_roleid'): # account already has RoleId , nothing to do return {'ret': True, 'changed': False} payload = {'RoleId': user.get('account_roleid')} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_password(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'Password': user['account_password']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_name(self, user): if not user.get('account_updatename'): return {'ret': False, 'msg': 'Must provide account_updatename for UpdateUserName command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'UserName': user['account_updatename']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_accountservice_properties(self, user): if user.get('account_properties') is None: return {'ret': False, 'msg': 'Must provide account_properties for UpdateAccountServiceProperties command'} account_properties = user.get('account_properties') # Find AccountService response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} accountservice_uri = data["AccountService"]["@odata.id"] # Check support or not response = self.get_request(self.root_uri + accountservice_uri) if response['ret'] is False: return response data = response['data'] for property_name in account_properties.keys(): if property_name not in data: return {'ret': False, 'msg': 'property %s not supported' % property_name} # if properties is already matched, nothing to do need_change = False for property_name in account_properties.keys(): if account_properties[property_name] != data[property_name]: need_change = True break if not need_change: return {'ret': True, 'changed': False, 'msg': "AccountService properties already set"} payload = account_properties response = self.patch_request(self.root_uri + accountservice_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified AccountService properties"} def get_sessions(self): result = {} # listing all users has always been slower than other operations, why? session_list = [] sessions_results = [] # Get these entries, but does not fail if not found properties = ['Description', 'Id', 'Name', 'UserName'] response = self.get_request(self.root_uri + self.sessions_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for sessions in data[u'Members']: session_list.append(sessions[u'@odata.id']) # session_list[] are URIs # for each session, get details for uri in session_list: session = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: session[property] = data[property] sessions_results.append(session) result["entries"] = sessions_results return result def get_firmware_update_capabilities(self): result = {} response = self.get_request(self.root_uri + self.update_uri) if response['ret'] is False: return response result['ret'] = True result['entries'] = {} data = response['data'] if "Actions" in data: actions = data['Actions'] if len(actions) > 0: for key in actions.keys(): action = actions.get(key) if 'title' in action: title = action['title'] else: title = key result['entries'][title] = action.get('[email protected]', ["Key [email protected] not found"]) else: return {'ret': "False", 'msg': "Actions list is empty."} else: return {'ret': "False", 'msg': "Key Actions not found."} return result def get_firmware_inventory(self): result = {} response = self.get_request(self.root_uri + self.firmware_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] result['entries'] = [] for device in data[u'Members']: uri = self.root_uri + device[u'@odata.id'] # Get details for each device response = self.get_request(uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] firmware = {} # Get these standard properties if present for key in ['Name', 'Id', 'Status', 'Version', 'Updateable', 'SoftwareId', 'LowestSupportedVersion', 'Manufacturer', 'ReleaseDate']: if key in data: firmware[key] = data.get(key) result['entries'].append(firmware) return result def get_bios_attributes(self, systems_uri): result = {} bios_attributes = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for attribute in data[u'Attributes'].items(): bios_attributes[attribute[0]] = attribute[1] result["entries"] = bios_attributes return result def get_multi_bios_attributes(self): return self.aggregate(self.get_bios_attributes) def _get_boot_options_dict(self, boot): # Get these entries from BootOption, if present properties = ['DisplayName', 'BootOptionReference'] # Retrieve BootOptions if present if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']: boot_options_uri = boot['BootOptions']["@odata.id"] # Get BootOptions resource response = self.get_request(self.root_uri + boot_options_uri) if response['ret'] is False: return {} data = response['data'] # Retrieve Members array if 'Members' not in data: return {} members = data['Members'] else: members = [] # Build dict of BootOptions keyed by BootOptionReference boot_options_dict = {} for member in members: if '@odata.id' not in member: return {} boot_option_uri = member['@odata.id'] response = self.get_request(self.root_uri + boot_option_uri) if response['ret'] is False: return {} data = response['data'] if 'BootOptionReference' not in data: return {} boot_option_ref = data['BootOptionReference'] # fetch the props to display for this boot device boot_props = {} for prop in properties: if prop in data: boot_props[prop] = data[prop] boot_options_dict[boot_option_ref] = boot_props return boot_options_dict def get_boot_order(self, systems_uri): result = {} # Retrieve System resource response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # Build boot device list boot_device_list = [] for ref in boot_order: boot_device_list.append( boot_options_dict.get(ref, {'BootOptionReference': ref})) result["entries"] = boot_device_list return result def get_multi_boot_order(self): return self.aggregate(self.get_boot_order) def get_boot_override(self, systems_uri): result = {} properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget", "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "[email protected]"] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Boot' not in data: return {'ret': False, 'msg': "Key Boot not found"} boot = data['Boot'] boot_overrides = {} if "BootSourceOverrideEnabled" in boot: if boot["BootSourceOverrideEnabled"] is not False: for property in properties: if property in boot: if boot[property] is not None: boot_overrides[property] = boot[property] else: return {'ret': False, 'msg': "No boot override is enabled."} result['entries'] = boot_overrides return result def get_multi_boot_override(self): return self.aggregate(self.get_boot_override) def set_bios_default_settings(self): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] reset_bios_settings_uri = data["Actions"]["#Bios.ResetBios"]["target"] response = self.post_request(self.root_uri + reset_bios_settings_uri, {}) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Set BIOS to default settings"} def set_one_time_boot_device(self, bootdevice, uefi_target, boot_next): result = {} key = "Boot" if not bootdevice: return {'ret': False, 'msg': "bootdevice option required for SetOneTimeBoot"} # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} boot = data[key] annotation = '[email protected]' if annotation in boot: allowable_values = boot[annotation] if isinstance(allowable_values, list) and bootdevice not in allowable_values: return {'ret': False, 'msg': "Boot device %s not in list of allowable values (%s)" % (bootdevice, allowable_values)} # read existing values enabled = boot.get('BootSourceOverrideEnabled') target = boot.get('BootSourceOverrideTarget') cur_uefi_target = boot.get('UefiTargetBootSourceOverride') cur_boot_next = boot.get('BootNext') if bootdevice == 'UefiTarget': if not uefi_target: return {'ret': False, 'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"} if enabled == 'Once' and target == bootdevice and uefi_target == cur_uefi_target: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'UefiTargetBootSourceOverride': uefi_target } } elif bootdevice == 'UefiBootNext': if not boot_next: return {'ret': False, 'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"} if enabled == 'Once' and target == bootdevice and boot_next == cur_boot_next: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'BootNext': boot_next } } else: if enabled == 'Once' and target == bootdevice: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice } } response = self.patch_request(self.root_uri + self.systems_uris[0], payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def set_bios_attributes(self, attr): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # First, check if BIOS attribute exists if attr['bios_attr_name'] not in data[u'Attributes']: return {'ret': False, 'msg': "BIOS attribute not found"} # Find out if value is already set to what we want. If yes, return if data[u'Attributes'][attr['bios_attr_name']] == attr['bios_attr_value']: return {'ret': True, 'changed': False, 'msg': "BIOS attribute already set"} set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"]["@odata.id"] # Example: bios_attr = {\"name\":\"value\"} bios_attr = "{\"" + attr['bios_attr_name'] + "\":\"" + attr['bios_attr_value'] + "\"}" payload = {"Attributes": json.loads(bios_attr)} response = self.patch_request(self.root_uri + set_bios_attr_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified BIOS attribute"} def set_boot_order(self, boot_list): if not boot_list: return {'ret': False, 'msg': "boot_order list required for SetBootOrder command"} # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # validate boot_list against BootOptionReferences if available if boot_options_dict: boot_option_references = boot_options_dict.keys() for ref in boot_list: if ref not in boot_option_references: return {'ret': False, 'msg': "BootOptionReference %s not found in BootOptions" % ref} # If requested BootOrder is already set, nothing to do if boot_order == boot_list: return {'ret': True, 'changed': False, 'msg': "BootOrder already set to %s" % boot_list} payload = { 'Boot': { 'BootOrder': boot_list } } response = self.patch_request(self.root_uri + systems_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set"} def set_default_boot_order(self): # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # get the #ComputerSystem.SetDefaultBootOrder Action and target URI action = '#ComputerSystem.SetDefaultBootOrder' if 'Actions' not in data or action not in data['Actions']: return {'ret': False, 'msg': 'Action %s not found' % action} if 'target' not in data['Actions'][action]: return {'ret': False, 'msg': 'target URI missing from Action %s' % action} action_uri = data['Actions'][action]['target'] # POST to Action URI payload = {} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set to default"} def get_chassis_inventory(self): result = {} chassis_results = [] # Get these entries, but does not fail if not found properties = ['ChassisType', 'PartNumber', 'AssetTag', 'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] chassis_result = {} for property in properties: if property in data: chassis_result[property] = data[property] chassis_results.append(chassis_result) result["entries"] = chassis_results return result def get_fan_inventory(self): result = {} fan_results = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['FanName', 'Reading', 'ReadingUnits', 'Status'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: # match: found an entry for "Thermal" information = fans thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for device in data[u'Fans']: fan = {} for property in properties: if property in device: fan[property] = device[property] fan_results.append(fan) result["entries"] = fan_results return result def get_chassis_power(self): result = {} key = "Power" # Get these entries, but does not fail if not found properties = ['Name', 'PowerAllocatedWatts', 'PowerAvailableWatts', 'PowerCapacityWatts', 'PowerConsumedWatts', 'PowerMetrics', 'PowerRequestedWatts', 'RelatedItem', 'Status'] chassis_power_results = [] # Go through list for chassis_uri in self.chassis_uri_list: chassis_power_result = {} response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: response = self.get_request(self.root_uri + data[key]['@odata.id']) data = response['data'] if 'PowerControl' in data: if len(data['PowerControl']) > 0: data = data['PowerControl'][0] for property in properties: if property in data: chassis_power_result[property] = data[property] else: return {'ret': False, 'msg': 'Key PowerControl not found.'} chassis_power_results.append(chassis_power_result) else: return {'ret': False, 'msg': 'Key Power not found.'} result['entries'] = chassis_power_results return result def get_chassis_thermals(self): result = {} sensors = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical', 'UpperThresholdFatal', 'UpperThresholdNonCritical', 'LowerThresholdCritical', 'LowerThresholdFatal', 'LowerThresholdNonCritical', 'MaxReadingRangeTemp', 'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem', 'SensorNumber'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if "Temperatures" in data: for sensor in data[u'Temperatures']: sensor_result = {} for property in properties: if property in sensor: if sensor[property] is not None: sensor_result[property] = sensor[property] sensors.append(sensor_result) if sensors is None: return {'ret': False, 'msg': 'Key Temperatures was not found.'} result['entries'] = sensors return result def get_cpu_inventory(self, systems_uri): result = {} cpu_list = [] cpu_results = [] key = "Processors" # Get these entries, but does not fail if not found properties = ['Id', 'Manufacturer', 'Model', 'MaxSpeedMHz', 'TotalCores', 'TotalThreads', 'Status'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} processors_uri = data[key]["@odata.id"] # Get a list of all CPUs and build respective URIs response = self.get_request(self.root_uri + processors_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for cpu in data[u'Members']: cpu_list.append(cpu[u'@odata.id']) for c in cpu_list: cpu = {} uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: cpu[property] = data[property] cpu_results.append(cpu) result["entries"] = cpu_results return result def get_multi_cpu_inventory(self): return self.aggregate(self.get_cpu_inventory) def get_memory_inventory(self, systems_uri): result = {} memory_list = [] memory_results = [] key = "Memory" # Get these entries, but does not fail if not found properties = ['SerialNumber', 'MemoryDeviceType', 'PartNuber', 'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} memory_uri = data[key]["@odata.id"] # Get a list of all DIMMs and build respective URIs response = self.get_request(self.root_uri + memory_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for dimm in data[u'Members']: memory_list.append(dimm[u'@odata.id']) for m in memory_list: dimm = {} uri = self.root_uri + m response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if "Status" in data: if "State" in data["Status"]: if data["Status"]["State"] == "Absent": continue else: continue for property in properties: if property in data: dimm[property] = data[property] memory_results.append(dimm) result["entries"] = memory_results return result def get_multi_memory_inventory(self): return self.aggregate(self.get_memory_inventory) def get_nic_inventory(self, resource_uri): result = {} nic_list = [] nic_results = [] key = "EthernetInterfaces" # Get these entries, but does not fail if not found properties = ['Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses', 'NameServers', 'MACAddress', 'PermanentMACAddress', 'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} ethernetinterfaces_uri = data[key]["@odata.id"] # Get a list of all network controllers and build respective URIs response = self.get_request(self.root_uri + ethernetinterfaces_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for nic in data[u'Members']: nic_list.append(nic[u'@odata.id']) for n in nic_list: nic = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: nic[property] = data[property] nic_results.append(nic) result["entries"] = nic_results return result def get_multi_nic_inventory(self, resource_type): ret = True entries = [] # Given resource_type, use the proper URI if resource_type == 'Systems': resource_uris = self.systems_uris elif resource_type == 'Manager': # put in a list to match what we're doing with systems_uris resource_uris = [self.manager_uri] for resource_uri in resource_uris: inventory = self.get_nic_inventory(resource_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'resource_uri': resource_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_virtualmedia(self, resource_uri): result = {} virtualmedia_list = [] virtualmedia_results = [] key = "VirtualMedia" # Get these entries, but does not fail if not found properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes', 'Image', 'ImageName', 'Name', 'WriteProtected', 'TransferMethod', 'TransferProtocolType'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} virtualmedia_uri = data[key]["@odata.id"] # Get a list of all virtual media and build respective URIs response = self.get_request(self.root_uri + virtualmedia_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for virtualmedia in data[u'Members']: virtualmedia_list.append(virtualmedia[u'@odata.id']) for n in virtualmedia_list: virtualmedia = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: virtualmedia[property] = data[property] virtualmedia_results.append(virtualmedia) result["entries"] = virtualmedia_results return result def get_multi_virtualmedia(self): ret = True entries = [] # Because _find_managers_resource() only find last Manager uri in self.manager_uri, not one list. This should be 1 issue. # I have to put manager_uri into list to reduce future changes when the issue is fixed. resource_uris = [self.manager_uri] for resource_uri in resource_uris: virtualmedia = self.get_virtualmedia(resource_uri) ret = virtualmedia.pop('ret') and ret if 'entries' in virtualmedia: entries.append(({'resource_uri': resource_uri}, virtualmedia['entries'])) return dict(ret=ret, entries=entries) def get_psu_inventory(self): result = {} psu_list = [] psu_results = [] key = "PowerSupplies" # Get these entries, but does not fail if not found properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status'] # Get a list of all Chassis and build URIs, then get all PowerSupplies # from each Power entry in the Chassis chassis_uri_list = self.chassis_uri_list for chassis_uri in chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Power' in data: power_uri = data[u'Power'][u'@odata.id'] else: continue response = self.get_request(self.root_uri + power_uri) data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} psu_list = data[key] for psu in psu_list: psu_not_present = False psu_data = {} for property in properties: if property in psu: if psu[property] is not None: if property == 'Status': if 'State' in psu[property]: if psu[property]['State'] == 'Absent': psu_not_present = True psu_data[property] = psu[property] if psu_not_present: continue psu_results.append(psu_data) result["entries"] = psu_results if not result["entries"]: return {'ret': False, 'msg': "No PowerSupply objects found"} return result def get_multi_psu_inventory(self): return self.aggregate(self.get_psu_inventory) def get_system_inventory(self, systems_uri): result = {} inventory = {} # Get these entries, but does not fail if not found properties = ['Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag', 'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary', 'ProcessorSummary', 'TrustedModules'] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for property in properties: if property in data: inventory[property] = data[property] result["entries"] = inventory return result def get_multi_system_inventory(self): return self.aggregate(self.get_system_inventory)
closed
ansible/ansible
https://github.com/ansible/ansible
59,793
Add GetSoftwareInventory command
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> During the 2019 APTS Plugfest, it was noted that the `GetFirmwareInventory` command was gathering the `FirmwareInventory` from the `UpdateService`, but not the `SoftwareInventory`. There are two options to address this request: 1. Update the `GetFirmwareInventory` command to also gather the `SoftwareInventory`. 2. Add a new `GetSoftwareInventory` command. I'll get input on these two options. [Per Tools Task Force call, agreed on option 2.] ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_facts.py redfish_utils.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Operators want to be able to get `SoftwareInventory` as well as `FirmwareInventory`. There is currently no way the gather the `SoftwareInventory` using the Ansible Redfish modules. <!--- Paste example playbooks or commands between quotes below --> **Option 1:** ```yaml tasks: - name: Get Firmware and Software Inventory redfish_facts: category: Update command: GetFirmwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result ``` **Option 2:** ```yaml tasks: - name: Get Firmware Inventory redfish_facts: category: Update command: GetFirmwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - name: Get Software Inventory redfish_facts: category: Update command: GetSoftwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/59793
https://github.com/ansible/ansible/pull/62811
31f3a29613d47908939e863d953a55c9dc7bada1
c9a669e42c3fd90ec9d6d28c60a0f56f1bd302a8
2019-07-30T16:02:33Z
python
2019-10-29T13:15:42Z
lib/ansible/modules/remote_management/redfish/redfish_info.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_info version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to get information back. - Information retrieved is placed in a location specified by the user. - This module was called C(redfish_facts) before Ansible 2.9, returning C(ansible_facts). Note that the M(redfish_info) module no longer returns C(ansible_facts)! options: category: required: false description: - List of categories to execute on OOB controller default: ['Systems'] type: list command: required: false description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - User for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: '2.8' author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Get CPU inventory redfish_info: category: Systems command: GetCpuInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.cpu.entries | to_nice_json }}" - name: Get CPU model redfish_info: category: Systems command: GetCpuInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.cpu.entries.0.Model }}" - name: Get memory inventory redfish_info: category: Systems command: GetMemoryInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - name: Get fan inventory with a timeout of 20 seconds redfish_info: category: Chassis command: GetFanInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 register: result - name: Get Virtual Media information redfish_info: category: Manager command: GetVirtualMedia baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.virtual_media.entries | to_nice_json }}" - name: Get Volume Inventory redfish_info: category: Systems command: GetVolumeInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.volume.entries | to_nice_json }}" - name: Get Session information redfish_info: category: Sessions command: GetSessions baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.session.entries | to_nice_json }}" - name: Get default inventory information redfish_info: baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts | to_nice_json }}" - name: Get several inventories redfish_info: category: Systems command: GetNicInventory,GetBiosAttributes baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get default system inventory and user information redfish_info: category: Systems,Accounts baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get default system, user and firmware information redfish_info: category: ["Systems", "Accounts", "Update"] baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get Manager NIC inventory information redfish_info: category: Manager command: GetManagerNicInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get boot override information redfish_info: category: Systems command: GetBootOverride baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get chassis inventory redfish_info: category: Chassis command: GetChassisInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get all information available in the Manager category redfish_info: category: Manager command: all baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get firmware update capability information redfish_info: category: Update command: GetFirmwareUpdateCapabilities baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get all information available in all categories redfish_info: category: all command: all baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ''' RETURN = ''' result: description: different results depending on task returned: always type: dict sample: List of CPUs on system ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils CATEGORY_COMMANDS_ALL = { "Systems": ["GetSystemInventory", "GetPsuInventory", "GetCpuInventory", "GetMemoryInventory", "GetNicInventory", "GetStorageControllerInventory", "GetDiskInventory", "GetVolumeInventory", "GetBiosAttributes", "GetBootOrder", "GetBootOverride"], "Chassis": ["GetFanInventory", "GetPsuInventory", "GetChassisPower", "GetChassisThermals", "GetChassisInventory"], "Accounts": ["ListUsers"], "Sessions": ["GetSessions"], "Update": ["GetFirmwareInventory", "GetFirmwareUpdateCapabilities"], "Manager": ["GetManagerNicInventory", "GetVirtualMedia", "GetLogs"], } CATEGORY_COMMANDS_DEFAULT = { "Systems": "GetSystemInventory", "Chassis": "GetFanInventory", "Accounts": "ListUsers", "Update": "GetFirmwareInventory", "Sessions": "GetSessions", "Manager": "GetManagerNicInventory" } def main(): result = {} category_list = [] module = AnsibleModule( argument_spec=dict( category=dict(type='list', default=['Systems']), command=dict(type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), timeout=dict(type='int', default=10) ), supports_check_mode=False ) is_old_facts = module._name == 'redfish_facts' if is_old_facts: module.deprecate("The 'redfish_facts' module has been renamed to 'redfish_info', " "and the renamed one no longer returns ansible_facts", version='2.13') # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Build Category list if "all" in module.params['category']: for entry in CATEGORY_COMMANDS_ALL: category_list.append(entry) else: # one or more categories specified category_list = module.params['category'] for category in category_list: command_list = [] # Build Command list for each Category if category in CATEGORY_COMMANDS_ALL: if not module.params['command']: # True if we don't specify a command --> use default command_list.append(CATEGORY_COMMANDS_DEFAULT[category]) elif "all" in module.params['command']: for entry in range(len(CATEGORY_COMMANDS_ALL[category])): command_list.append(CATEGORY_COMMANDS_ALL[category][entry]) # one or more commands else: command_list = module.params['command'] # Verify that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg="Invalid Command: %s" % cmd) else: # Fail if even one category given is invalid module.fail_json(msg="Invalid Category: %s" % category) # Organize by Categories / Commands if category == "Systems": # execute only if we find a Systems resource resource = rf_utils._find_systems_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetSystemInventory": result["system"] = rf_utils.get_multi_system_inventory() elif command == "GetCpuInventory": result["cpu"] = rf_utils.get_multi_cpu_inventory() elif command == "GetMemoryInventory": result["memory"] = rf_utils.get_multi_memory_inventory() elif command == "GetNicInventory": result["nic"] = rf_utils.get_multi_nic_inventory(category) elif command == "GetStorageControllerInventory": result["storage_controller"] = rf_utils.get_multi_storage_controller_inventory() elif command == "GetDiskInventory": result["disk"] = rf_utils.get_multi_disk_inventory() elif command == "GetVolumeInventory": result["volume"] = rf_utils.get_multi_volume_inventory() elif command == "GetBiosAttributes": result["bios_attribute"] = rf_utils.get_multi_bios_attributes() elif command == "GetBootOrder": result["boot_order"] = rf_utils.get_multi_boot_order() elif command == "GetBootOverride": result["boot_override"] = rf_utils.get_multi_boot_override() elif category == "Chassis": # execute only if we find Chassis resource resource = rf_utils._find_chassis_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetFanInventory": result["fan"] = rf_utils.get_fan_inventory() elif command == "GetPsuInventory": result["psu"] = rf_utils.get_psu_inventory() elif command == "GetChassisThermals": result["thermals"] = rf_utils.get_chassis_thermals() elif command == "GetChassisPower": result["chassis_power"] = rf_utils.get_chassis_power() elif command == "GetChassisInventory": result["chassis"] = rf_utils.get_chassis_inventory() elif category == "Accounts": # execute only if we find an Account service resource resource = rf_utils._find_accountservice_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "ListUsers": result["user"] = rf_utils.list_users() elif category == "Update": # execute only if we find UpdateService resources resource = rf_utils._find_updateservice_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetFirmwareInventory": result["firmware"] = rf_utils.get_firmware_inventory() elif command == "GetFirmwareUpdateCapabilities": result["firmware_update_capabilities"] = rf_utils.get_firmware_update_capabilities() elif category == "Sessions": # execute only if we find SessionService resources resource = rf_utils._find_sessionservice_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetSessions": result["session"] = rf_utils.get_sessions() elif category == "Manager": # execute only if we find a Manager service resource resource = rf_utils._find_managers_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetManagerNicInventory": result["manager_nics"] = rf_utils.get_multi_nic_inventory(category) elif command == "GetVirtualMedia": result["virtual_media"] = rf_utils.get_multi_virtualmedia() elif command == "GetLogs": result["log"] = rf_utils.get_logs() # Return data back if is_old_facts: module.exit_json(ansible_facts=dict(redfish_facts=result)) else: module.exit_json(redfish_facts=result) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
59,822
EnableUser command fails if no Enabled property is present
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When using the `EnableUser` command, if the account being targeted does not have an `Enabled` property, the command may fail with a `400 Bad Request`. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_command.py redfish_utils.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.0.dev0 config file = $HOME/.ansible.cfg configured module search path = ['$HOME/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = $HOME/Development/git/ansible/lib/ansible executable location = $HOME/Development/git/ansible/bin/ansible python version = 3.6.5 (default, Apr 25 2018, 14:26:36) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below [no output] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Applies to Redfish OOB controllers. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Try to run the EnableUser command for an account that does not have the `Enabled` property. <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: myhosts connection: local name: Enable User gather_facts: False vars: - account_username: user8 tasks: - name: Enable user redfish_command: category: Accounts command: EnableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Command succeeds with `changed=0`. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Command fails with: <!--- Paste verbatim command output between quotes --> ```paste below 400 Bad Request ```
https://github.com/ansible/ansible/issues/59822
https://github.com/ansible/ansible/pull/62617
c9a669e42c3fd90ec9d6d28c60a0f56f1bd302a8
14eedb2956a304d582da63e57b7663c61eb7a7a4
2019-07-30T20:39:22Z
python
2019-10-29T13:16:49Z
changelogs/fragments/62617-fix-redfish-enable-account-if-enabled-prop-missing.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
59,822
EnableUser command fails if no Enabled property is present
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When using the `EnableUser` command, if the account being targeted does not have an `Enabled` property, the command may fail with a `400 Bad Request`. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_command.py redfish_utils.py ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.9.0.dev0 config file = $HOME/.ansible.cfg configured module search path = ['$HOME/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = $HOME/Development/git/ansible/lib/ansible executable location = $HOME/Development/git/ansible/bin/ansible python version = 3.6.5 (default, Apr 25 2018, 14:26:36) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below [no output] ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Applies to Redfish OOB controllers. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Try to run the EnableUser command for an account that does not have the `Enabled` property. <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: myhosts connection: local name: Enable User gather_facts: False vars: - account_username: user8 tasks: - name: Enable user redfish_command: category: Accounts command: EnableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Command succeeds with `changed=0`. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Command fails with: <!--- Paste verbatim command output between quotes --> ```paste below 400 Bad Request ```
https://github.com/ansible/ansible/issues/59822
https://github.com/ansible/ansible/pull/62617
c9a669e42c3fd90ec9d6d28c60a0f56f1bd302a8
14eedb2956a304d582da63e57b7663c61eb7a7a4
2019-07-30T20:39:22Z
python
2019-10-29T13:16:49Z
lib/ansible/module_utils/redfish_utils.py
# Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import json from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import http_client from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} class RedfishUtils(object): def __init__(self, creds, root_uri, timeout, module): self.root_uri = root_uri self.creds = creds self.timeout = timeout self.module = module self.service_root = '/redfish/v1/' self._init_session() # The following functions are to send GET/POST/PATCH/DELETE requests def get_request(self, uri): try: resp = open_url(uri, method="GET", headers=GET_HEADERS, url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) data = json.loads(resp.read()) headers = dict((k.lower(), v) for (k, v) in resp.info().items()) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'data': data, 'headers': headers} def post_request(self, uri, pyld): try: resp = open_url(uri, data=json.dumps(pyld), headers=POST_HEADERS, method="POST", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def patch_request(self, uri, pyld): headers = PATCH_HEADERS r = self.get_request(uri) if r['ret']: # Get etag from etag header or @odata.etag property etag = r['headers'].get('etag') if not etag: etag = r['data'].get('@odata.etag') if etag: # Make copy of headers and add If-Match header headers = dict(headers) headers['If-Match'] = etag try: resp = open_url(uri, data=json.dumps(pyld), headers=headers, method="PATCH", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def delete_request(self, uri, pyld=None): try: data = json.dumps(pyld) if pyld else None resp = open_url(uri, data=data, headers=DELETE_HEADERS, method="DELETE", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} @staticmethod def _get_extended_message(error): """ Get Redfish ExtendedInfo message from response payload if present :param error: an HTTPError exception :type error: HTTPError :return: the ExtendedInfo message if present, else standard HTTP error """ msg = http_client.responses.get(error.code, '') if error.code >= 400: try: body = error.read().decode('utf-8') data = json.loads(body) ext_info = data['error']['@Message.ExtendedInfo'] msg = ext_info[0]['Message'] except Exception: pass return msg def _init_session(self): pass def _find_accountservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} else: account_service = data["AccountService"]["@odata.id"] response = self.get_request(self.root_uri + account_service) if response['ret'] is False: return response data = response['data'] accounts = data['Accounts']['@odata.id'] if accounts[-1:] == '/': accounts = accounts[:-1] self.accounts_uri = accounts return {'ret': True} def _find_sessionservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'SessionService' not in data: return {'ret': False, 'msg': "SessionService resource not found"} else: session_service = data["SessionService"]["@odata.id"] response = self.get_request(self.root_uri + session_service) if response['ret'] is False: return response data = response['data'] sessions = data['Sessions']['@odata.id'] if sessions[-1:] == '/': sessions = sessions[:-1] self.sessions_uri = sessions return {'ret': True} def _find_systems_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Systems' not in data: return {'ret': False, 'msg': "Systems resource not found"} response = self.get_request(self.root_uri + data['Systems']['@odata.id']) if response['ret'] is False: return response self.systems_uris = [ i['@odata.id'] for i in response['data'].get('Members', [])] if not self.systems_uris: return { 'ret': False, 'msg': "ComputerSystem's Members array is either empty or missing"} return {'ret': True} def _find_updateservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'UpdateService' not in data: return {'ret': False, 'msg': "UpdateService resource not found"} else: update = data["UpdateService"]["@odata.id"] self.update_uri = update response = self.get_request(self.root_uri + update) if response['ret'] is False: return response data = response['data'] self.firmware_uri = self.software_uri = None if 'FirmwareInventory' in data: self.firmware_uri = data['FirmwareInventory'][u'@odata.id'] if 'SoftwareInventory' in data: self.software_uri = data['SoftwareInventory'][u'@odata.id'] return {'ret': True} def _find_chassis_resource(self): chassis_service = [] response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Chassis' not in data: return {'ret': False, 'msg': "Chassis resource not found"} else: chassis = data["Chassis"]["@odata.id"] response = self.get_request(self.root_uri + chassis) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: chassis_service.append(member[u'@odata.id']) self.chassis_uri_list = chassis_service return {'ret': True} def _find_managers_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Managers' not in data: return {'ret': False, 'msg': "Manager resource not found"} else: manager = data["Managers"]["@odata.id"] response = self.get_request(self.root_uri + manager) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: manager_service = member[u'@odata.id'] self.manager_uri = manager_service return {'ret': True} def get_logs(self): log_svcs_uri_list = [] list_of_logs = [] properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat', 'Message', 'MessageId', 'MessageArgs'] # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data.get('Members', []): response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id']) if response['ret'] is False: return response _data = response['data'] if 'Entries' in _data: log_svcs_uri_list.append(_data['Entries'][u'@odata.id']) # For each entry in LogServices, get log name and all log entries for log_svcs_uri in log_svcs_uri_list: logs = {} list_of_log_entries = [] response = self.get_request(self.root_uri + log_svcs_uri) if response['ret'] is False: return response data = response['data'] logs['Description'] = data.get('Description', 'Collection of log entries') # Get all log entries for each type of log found for logEntry in data.get('Members', []): entry = {} for prop in properties: if prop in logEntry: entry[prop] = logEntry.get(prop) if entry: list_of_log_entries.append(entry) log_name = log_svcs_uri.split('/')[-1] logs[log_name] = list_of_log_entries list_of_logs.append(logs) # list_of_logs[logs{list_of_log_entries[entry{}]}] return {'ret': True, 'entries': list_of_logs} def clear_logs(self): # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data[u'Members']: response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"]) if response['ret'] is False: return response _data = response['data'] # Check to make sure option is available, otherwise error is ugly if "Actions" in _data: if "#LogService.ClearLog" in _data[u"Actions"]: self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {}) if response['ret'] is False: return response return {'ret': True} def aggregate(self, func): ret = True entries = [] for systems_uri in self.systems_uris: inventory = func(systems_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'systems_uri': systems_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_storage_controller_inventory(self, systems_uri): result = {} controller_list = [] controller_results = [] # Get these entries, but does not fail if not found properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers', 'Location', 'Manufacturer', 'Model', 'Name', 'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status'] key = "StorageControllers" # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'Storage' not in data: return {'ret': False, 'msg': "Storage resource not found"} # Get a list of all storage controllers and build respective URIs storage_uri = data['Storage']["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Loop through Members and their StorageControllers # and gather properties from each StorageController if data[u'Members']: for storage_member in data[u'Members']: storage_member_uri = storage_member[u'@odata.id'] response = self.get_request(self.root_uri + storage_member_uri) data = response['data'] if key in data: controller_list = data[key] for controller in controller_list: controller_result = {} for property in properties: if property in controller: controller_result[property] = controller[property] controller_results.append(controller_result) result['entries'] = controller_results return result else: return {'ret': False, 'msg': "Storage resource not found"} def get_multi_storage_controller_inventory(self): return self.aggregate(self.get_storage_controller_inventory) def get_disk_inventory(self, systems_uri): result = {'entries': []} controller_list = [] # Get these entries, but does not fail if not found properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes', 'EncryptionAbility', 'EncryptionStatus', 'FailurePredicted', 'HotspareType', 'Id', 'Identifiers', 'Manufacturer', 'MediaType', 'Model', 'Name', 'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision', 'RotationSpeedRPM', 'SerialNumber', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data[u'Members']: for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] if 'Drives' in data: for device in data[u'Drives']: disk_uri = self.root_uri + device[u'@odata.id'] response = self.get_request(disk_uri) data = response['data'] drive_result = {} for property in properties: if property in data: if data[property] is not None: drive_result[property] = data[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) if 'SimpleStorage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data["SimpleStorage"]["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Name' in data: controller_name = data['Name'] else: sc_id = data.get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] for device in data[u'Devices']: drive_result = {} for property in properties: if property in device: drive_result[property] = device[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) return result def get_multi_disk_inventory(self): return self.aggregate(self.get_disk_inventory) def get_volume_inventory(self, systems_uri): result = {'entries': []} controller_list = [] volume_list = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes', 'Capacity', 'CapacityBytes', 'CapacitySources', 'Encrypted', 'EncryptionTypes', 'Identifiers', 'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities', 'AllocatedPools', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data.get('Members'): for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id volume_results = [] if 'Volumes' in data: # Get a list of all volumes and build respective URIs volumes_uri = data[u'Volumes'][u'@odata.id'] response = self.get_request(self.root_uri + volumes_uri) data = response['data'] if data.get('Members'): for volume in data[u'Members']: volume_list.append(volume[u'@odata.id']) for v in volume_list: uri = self.root_uri + v response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] volume_result = {} for property in properties: if property in data: if data[property] is not None: volume_result[property] = data[property] # Get related Drives Id drive_id_list = [] if 'Links' in data: if 'Drives' in data[u'Links']: for link in data[u'Links'][u'Drives']: drive_id_link = link[u'@odata.id'] drive_id = drive_id_link.split("/")[-1] drive_id_list.append({'Id': drive_id}) volume_result['Linked_drives'] = drive_id_list volume_results.append(volume_result) volumes = {'Controller': controller_name, 'Volumes': volume_results} result["entries"].append(volumes) else: return {'ret': False, 'msg': "Storage resource not found"} return result def get_multi_volume_inventory(self): return self.aggregate(self.get_volume_inventory) def restart_manager_gracefully(self): result = {} key = "Actions" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] action_uri = data[key]["#Manager.Reset"]["target"] payload = {'ResetType': 'GracefulRestart'} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True} def manage_indicator_led(self, command): result = {} key = 'IndicatorLED' payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'} result = {} for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} if command in payloads.keys(): payload = {'IndicatorLED': payloads[command]} response = self.patch_request(self.root_uri + chassis_uri, payload) if response['ret'] is False: return response else: return {'ret': False, 'msg': 'Invalid command'} return result def _map_reset_type(self, reset_type, allowable_values): equiv_types = { 'On': 'ForceOn', 'ForceOn': 'On', 'ForceOff': 'GracefulShutdown', 'GracefulShutdown': 'ForceOff', 'GracefulRestart': 'ForceRestart', 'ForceRestart': 'GracefulRestart' } if reset_type in allowable_values: return reset_type if reset_type not in equiv_types: return reset_type mapped_type = equiv_types[reset_type] if mapped_type in allowable_values: return mapped_type return reset_type def manage_system_power(self, command): key = "Actions" reset_type_values = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] # command should be PowerOn, PowerForceOff, etc. if not command.startswith('Power'): return {'ret': False, 'msg': 'Invalid Command (%s)' % command} reset_type = command[5:] # map Reboot to a ResetType that does a reboot if reset_type == 'Reboot': reset_type = 'GracefulRestart' if reset_type not in reset_type_values: return {'ret': False, 'msg': 'Invalid Command (%s)' % command} # read the system resource and get the current power state response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response data = response['data'] power_state = data.get('PowerState') # if power is already in target state, nothing to do if power_state == "On" and reset_type in ['On', 'ForceOn']: return {'ret': True, 'changed': False} if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']: return {'ret': True, 'changed': False} # get the #ComputerSystem.Reset Action and target URI if key not in data or '#ComputerSystem.Reset' not in data[key]: return {'ret': False, 'msg': 'Action #ComputerSystem.Reset not found'} reset_action = data[key]['#ComputerSystem.Reset'] if 'target' not in reset_action: return {'ret': False, 'msg': 'target URI missing from Action #ComputerSystem.Reset'} action_uri = reset_action['target'] # get AllowableValues from ActionInfo allowable_values = None if '@Redfish.ActionInfo' in reset_action: action_info_uri = reset_action.get('@Redfish.ActionInfo') response = self.get_request(self.root_uri + action_info_uri) if response['ret'] is True: data = response['data'] if 'Parameters' in data: params = data['Parameters'] for param in params: if param.get('Name') == 'ResetType': allowable_values = param.get('AllowableValues') break # fallback to @Redfish.AllowableValues annotation if allowable_values is None: allowable_values = reset_action.get('[email protected]', []) # map ResetType to an allowable value if needed if reset_type not in allowable_values: reset_type = self._map_reset_type(reset_type, allowable_values) # define payload payload = {'ResetType': reset_type} # POST to Action URI response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def _find_account_uri(self, username=None, acct_id=None): if not any((username, acct_id)): return {'ret': False, 'msg': 'Must provide either account_id or account_username'} response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if username: if username == data.get('UserName'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} if acct_id: if acct_id == data.get('Id'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No account with the given account_id or account_username found'} def _find_empty_account_slot(self): response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] if uris: # first slot may be reserved, so move to end of list uris += [uris.pop(0)] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if data.get('UserName') == "" and not data.get('Enabled', True): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No empty account slot found'} def list_users(self): result = {} # listing all users has always been slower than other operations, why? user_list = [] users_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled'] response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for users in data.get('Members', []): user_list.append(users[u'@odata.id']) # user_list[] are URIs # for each user, get details for uri in user_list: user = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: user[property] = data[property] users_results.append(user) result["entries"] = users_results return result def add_user_via_patch(self, user): if user.get('account_id'): # If Id slot specified, use it response = self._find_account_uri(acct_id=user.get('account_id')) else: # Otherwise find first empty slot response = self._find_empty_account_slot() if not response['ret']: return response uri = response['uri'] payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def add_user(self, user): if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_account_uri(username=user.get('account_username')) if response['ret']: # account_username already exists, nothing to do return {'ret': True, 'changed': False} response = self.get_request(self.root_uri + self.accounts_uri) if not response['ret']: return response headers = response['headers'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'POST' not in methods: # if Allow header present and POST not listed, add via PATCH return self.add_user_via_patch(user) payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.post_request(self.root_uri + self.accounts_uri, payload) if not response['ret']: if response.get('status') == 405: # if POST returned a 405, try to add via PATCH return self.add_user_via_patch(user) else: return response return {'ret': True} def enable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('Enabled'): # account already enabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': True} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user_via_patch(self, user, uri=None, data=None): if not uri: response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data and data.get('UserName') == '' and not data.get('Enabled', False): # account UserName already cleared, nothing to do return {'ret': True, 'changed': False} payload = {'UserName': ''} if 'Enabled' in data: payload['Enabled'] = False response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: if response.get('no_match'): # account does not exist, nothing to do return {'ret': True, 'changed': False} else: # some error encountered return response uri = response['uri'] headers = response['headers'] data = response['data'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'DELETE' not in methods: # if Allow header present and DELETE not listed, del via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) response = self.delete_request(self.root_uri + uri) if not response['ret']: if response.get('status') == 405: # if DELETE returned a 405, try to delete via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) else: return response return {'ret': True} def disable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if not data.get('Enabled'): # account already disabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': False} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_role(self, user): if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('RoleId') == user.get('account_roleid'): # account already has RoleId , nothing to do return {'ret': True, 'changed': False} payload = {'RoleId': user.get('account_roleid')} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_password(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'Password': user['account_password']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_name(self, user): if not user.get('account_updatename'): return {'ret': False, 'msg': 'Must provide account_updatename for UpdateUserName command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'UserName': user['account_updatename']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_accountservice_properties(self, user): if user.get('account_properties') is None: return {'ret': False, 'msg': 'Must provide account_properties for UpdateAccountServiceProperties command'} account_properties = user.get('account_properties') # Find AccountService response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} accountservice_uri = data["AccountService"]["@odata.id"] # Check support or not response = self.get_request(self.root_uri + accountservice_uri) if response['ret'] is False: return response data = response['data'] for property_name in account_properties.keys(): if property_name not in data: return {'ret': False, 'msg': 'property %s not supported' % property_name} # if properties is already matched, nothing to do need_change = False for property_name in account_properties.keys(): if account_properties[property_name] != data[property_name]: need_change = True break if not need_change: return {'ret': True, 'changed': False, 'msg': "AccountService properties already set"} payload = account_properties response = self.patch_request(self.root_uri + accountservice_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified AccountService properties"} def get_sessions(self): result = {} # listing all users has always been slower than other operations, why? session_list = [] sessions_results = [] # Get these entries, but does not fail if not found properties = ['Description', 'Id', 'Name', 'UserName'] response = self.get_request(self.root_uri + self.sessions_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for sessions in data[u'Members']: session_list.append(sessions[u'@odata.id']) # session_list[] are URIs # for each session, get details for uri in session_list: session = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: session[property] = data[property] sessions_results.append(session) result["entries"] = sessions_results return result def get_firmware_update_capabilities(self): result = {} response = self.get_request(self.root_uri + self.update_uri) if response['ret'] is False: return response result['ret'] = True result['entries'] = {} data = response['data'] if "Actions" in data: actions = data['Actions'] if len(actions) > 0: for key in actions.keys(): action = actions.get(key) if 'title' in action: title = action['title'] else: title = key result['entries'][title] = action.get('[email protected]', ["Key [email protected] not found"]) else: return {'ret': "False", 'msg': "Actions list is empty."} else: return {'ret': "False", 'msg': "Key Actions not found."} return result def _software_inventory(self, uri): result = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] result['entries'] = [] for member in data[u'Members']: uri = self.root_uri + member[u'@odata.id'] # Get details for each software or firmware member response = self.get_request(uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] software = {} # Get these standard properties if present for key in ['Name', 'Id', 'Status', 'Version', 'Updateable', 'SoftwareId', 'LowestSupportedVersion', 'Manufacturer', 'ReleaseDate']: if key in data: software[key] = data.get(key) result['entries'].append(software) return result def get_firmware_inventory(self): if self.firmware_uri is None: return {'ret': False, 'msg': 'No FirmwareInventory resource found'} else: return self._software_inventory(self.firmware_uri) def get_software_inventory(self): if self.software_uri is None: return {'ret': False, 'msg': 'No SoftwareInventory resource found'} else: return self._software_inventory(self.software_uri) def get_bios_attributes(self, systems_uri): result = {} bios_attributes = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for attribute in data[u'Attributes'].items(): bios_attributes[attribute[0]] = attribute[1] result["entries"] = bios_attributes return result def get_multi_bios_attributes(self): return self.aggregate(self.get_bios_attributes) def _get_boot_options_dict(self, boot): # Get these entries from BootOption, if present properties = ['DisplayName', 'BootOptionReference'] # Retrieve BootOptions if present if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']: boot_options_uri = boot['BootOptions']["@odata.id"] # Get BootOptions resource response = self.get_request(self.root_uri + boot_options_uri) if response['ret'] is False: return {} data = response['data'] # Retrieve Members array if 'Members' not in data: return {} members = data['Members'] else: members = [] # Build dict of BootOptions keyed by BootOptionReference boot_options_dict = {} for member in members: if '@odata.id' not in member: return {} boot_option_uri = member['@odata.id'] response = self.get_request(self.root_uri + boot_option_uri) if response['ret'] is False: return {} data = response['data'] if 'BootOptionReference' not in data: return {} boot_option_ref = data['BootOptionReference'] # fetch the props to display for this boot device boot_props = {} for prop in properties: if prop in data: boot_props[prop] = data[prop] boot_options_dict[boot_option_ref] = boot_props return boot_options_dict def get_boot_order(self, systems_uri): result = {} # Retrieve System resource response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # Build boot device list boot_device_list = [] for ref in boot_order: boot_device_list.append( boot_options_dict.get(ref, {'BootOptionReference': ref})) result["entries"] = boot_device_list return result def get_multi_boot_order(self): return self.aggregate(self.get_boot_order) def get_boot_override(self, systems_uri): result = {} properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget", "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "[email protected]"] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Boot' not in data: return {'ret': False, 'msg': "Key Boot not found"} boot = data['Boot'] boot_overrides = {} if "BootSourceOverrideEnabled" in boot: if boot["BootSourceOverrideEnabled"] is not False: for property in properties: if property in boot: if boot[property] is not None: boot_overrides[property] = boot[property] else: return {'ret': False, 'msg': "No boot override is enabled."} result['entries'] = boot_overrides return result def get_multi_boot_override(self): return self.aggregate(self.get_boot_override) def set_bios_default_settings(self): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] reset_bios_settings_uri = data["Actions"]["#Bios.ResetBios"]["target"] response = self.post_request(self.root_uri + reset_bios_settings_uri, {}) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Set BIOS to default settings"} def set_one_time_boot_device(self, bootdevice, uefi_target, boot_next): result = {} key = "Boot" if not bootdevice: return {'ret': False, 'msg': "bootdevice option required for SetOneTimeBoot"} # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} boot = data[key] annotation = '[email protected]' if annotation in boot: allowable_values = boot[annotation] if isinstance(allowable_values, list) and bootdevice not in allowable_values: return {'ret': False, 'msg': "Boot device %s not in list of allowable values (%s)" % (bootdevice, allowable_values)} # read existing values enabled = boot.get('BootSourceOverrideEnabled') target = boot.get('BootSourceOverrideTarget') cur_uefi_target = boot.get('UefiTargetBootSourceOverride') cur_boot_next = boot.get('BootNext') if bootdevice == 'UefiTarget': if not uefi_target: return {'ret': False, 'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"} if enabled == 'Once' and target == bootdevice and uefi_target == cur_uefi_target: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'UefiTargetBootSourceOverride': uefi_target } } elif bootdevice == 'UefiBootNext': if not boot_next: return {'ret': False, 'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"} if enabled == 'Once' and target == bootdevice and boot_next == cur_boot_next: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'BootNext': boot_next } } else: if enabled == 'Once' and target == bootdevice: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice } } response = self.patch_request(self.root_uri + self.systems_uris[0], payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def set_bios_attributes(self, attr): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # First, check if BIOS attribute exists if attr['bios_attr_name'] not in data[u'Attributes']: return {'ret': False, 'msg': "BIOS attribute not found"} # Find out if value is already set to what we want. If yes, return if data[u'Attributes'][attr['bios_attr_name']] == attr['bios_attr_value']: return {'ret': True, 'changed': False, 'msg': "BIOS attribute already set"} set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"]["@odata.id"] # Example: bios_attr = {\"name\":\"value\"} bios_attr = "{\"" + attr['bios_attr_name'] + "\":\"" + attr['bios_attr_value'] + "\"}" payload = {"Attributes": json.loads(bios_attr)} response = self.patch_request(self.root_uri + set_bios_attr_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified BIOS attribute"} def set_boot_order(self, boot_list): if not boot_list: return {'ret': False, 'msg': "boot_order list required for SetBootOrder command"} # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # validate boot_list against BootOptionReferences if available if boot_options_dict: boot_option_references = boot_options_dict.keys() for ref in boot_list: if ref not in boot_option_references: return {'ret': False, 'msg': "BootOptionReference %s not found in BootOptions" % ref} # If requested BootOrder is already set, nothing to do if boot_order == boot_list: return {'ret': True, 'changed': False, 'msg': "BootOrder already set to %s" % boot_list} payload = { 'Boot': { 'BootOrder': boot_list } } response = self.patch_request(self.root_uri + systems_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set"} def set_default_boot_order(self): # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # get the #ComputerSystem.SetDefaultBootOrder Action and target URI action = '#ComputerSystem.SetDefaultBootOrder' if 'Actions' not in data or action not in data['Actions']: return {'ret': False, 'msg': 'Action %s not found' % action} if 'target' not in data['Actions'][action]: return {'ret': False, 'msg': 'target URI missing from Action %s' % action} action_uri = data['Actions'][action]['target'] # POST to Action URI payload = {} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set to default"} def get_chassis_inventory(self): result = {} chassis_results = [] # Get these entries, but does not fail if not found properties = ['ChassisType', 'PartNumber', 'AssetTag', 'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] chassis_result = {} for property in properties: if property in data: chassis_result[property] = data[property] chassis_results.append(chassis_result) result["entries"] = chassis_results return result def get_fan_inventory(self): result = {} fan_results = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['FanName', 'Reading', 'ReadingUnits', 'Status'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: # match: found an entry for "Thermal" information = fans thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for device in data[u'Fans']: fan = {} for property in properties: if property in device: fan[property] = device[property] fan_results.append(fan) result["entries"] = fan_results return result def get_chassis_power(self): result = {} key = "Power" # Get these entries, but does not fail if not found properties = ['Name', 'PowerAllocatedWatts', 'PowerAvailableWatts', 'PowerCapacityWatts', 'PowerConsumedWatts', 'PowerMetrics', 'PowerRequestedWatts', 'RelatedItem', 'Status'] chassis_power_results = [] # Go through list for chassis_uri in self.chassis_uri_list: chassis_power_result = {} response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: response = self.get_request(self.root_uri + data[key]['@odata.id']) data = response['data'] if 'PowerControl' in data: if len(data['PowerControl']) > 0: data = data['PowerControl'][0] for property in properties: if property in data: chassis_power_result[property] = data[property] else: return {'ret': False, 'msg': 'Key PowerControl not found.'} chassis_power_results.append(chassis_power_result) else: return {'ret': False, 'msg': 'Key Power not found.'} result['entries'] = chassis_power_results return result def get_chassis_thermals(self): result = {} sensors = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical', 'UpperThresholdFatal', 'UpperThresholdNonCritical', 'LowerThresholdCritical', 'LowerThresholdFatal', 'LowerThresholdNonCritical', 'MaxReadingRangeTemp', 'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem', 'SensorNumber'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if "Temperatures" in data: for sensor in data[u'Temperatures']: sensor_result = {} for property in properties: if property in sensor: if sensor[property] is not None: sensor_result[property] = sensor[property] sensors.append(sensor_result) if sensors is None: return {'ret': False, 'msg': 'Key Temperatures was not found.'} result['entries'] = sensors return result def get_cpu_inventory(self, systems_uri): result = {} cpu_list = [] cpu_results = [] key = "Processors" # Get these entries, but does not fail if not found properties = ['Id', 'Manufacturer', 'Model', 'MaxSpeedMHz', 'TotalCores', 'TotalThreads', 'Status'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} processors_uri = data[key]["@odata.id"] # Get a list of all CPUs and build respective URIs response = self.get_request(self.root_uri + processors_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for cpu in data[u'Members']: cpu_list.append(cpu[u'@odata.id']) for c in cpu_list: cpu = {} uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: cpu[property] = data[property] cpu_results.append(cpu) result["entries"] = cpu_results return result def get_multi_cpu_inventory(self): return self.aggregate(self.get_cpu_inventory) def get_memory_inventory(self, systems_uri): result = {} memory_list = [] memory_results = [] key = "Memory" # Get these entries, but does not fail if not found properties = ['SerialNumber', 'MemoryDeviceType', 'PartNuber', 'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} memory_uri = data[key]["@odata.id"] # Get a list of all DIMMs and build respective URIs response = self.get_request(self.root_uri + memory_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for dimm in data[u'Members']: memory_list.append(dimm[u'@odata.id']) for m in memory_list: dimm = {} uri = self.root_uri + m response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if "Status" in data: if "State" in data["Status"]: if data["Status"]["State"] == "Absent": continue else: continue for property in properties: if property in data: dimm[property] = data[property] memory_results.append(dimm) result["entries"] = memory_results return result def get_multi_memory_inventory(self): return self.aggregate(self.get_memory_inventory) def get_nic_inventory(self, resource_uri): result = {} nic_list = [] nic_results = [] key = "EthernetInterfaces" # Get these entries, but does not fail if not found properties = ['Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses', 'NameServers', 'MACAddress', 'PermanentMACAddress', 'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} ethernetinterfaces_uri = data[key]["@odata.id"] # Get a list of all network controllers and build respective URIs response = self.get_request(self.root_uri + ethernetinterfaces_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for nic in data[u'Members']: nic_list.append(nic[u'@odata.id']) for n in nic_list: nic = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: nic[property] = data[property] nic_results.append(nic) result["entries"] = nic_results return result def get_multi_nic_inventory(self, resource_type): ret = True entries = [] # Given resource_type, use the proper URI if resource_type == 'Systems': resource_uris = self.systems_uris elif resource_type == 'Manager': # put in a list to match what we're doing with systems_uris resource_uris = [self.manager_uri] for resource_uri in resource_uris: inventory = self.get_nic_inventory(resource_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'resource_uri': resource_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_virtualmedia(self, resource_uri): result = {} virtualmedia_list = [] virtualmedia_results = [] key = "VirtualMedia" # Get these entries, but does not fail if not found properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes', 'Image', 'ImageName', 'Name', 'WriteProtected', 'TransferMethod', 'TransferProtocolType'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} virtualmedia_uri = data[key]["@odata.id"] # Get a list of all virtual media and build respective URIs response = self.get_request(self.root_uri + virtualmedia_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for virtualmedia in data[u'Members']: virtualmedia_list.append(virtualmedia[u'@odata.id']) for n in virtualmedia_list: virtualmedia = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: virtualmedia[property] = data[property] virtualmedia_results.append(virtualmedia) result["entries"] = virtualmedia_results return result def get_multi_virtualmedia(self): ret = True entries = [] # Because _find_managers_resource() only find last Manager uri in self.manager_uri, not one list. This should be 1 issue. # I have to put manager_uri into list to reduce future changes when the issue is fixed. resource_uris = [self.manager_uri] for resource_uri in resource_uris: virtualmedia = self.get_virtualmedia(resource_uri) ret = virtualmedia.pop('ret') and ret if 'entries' in virtualmedia: entries.append(({'resource_uri': resource_uri}, virtualmedia['entries'])) return dict(ret=ret, entries=entries) def get_psu_inventory(self): result = {} psu_list = [] psu_results = [] key = "PowerSupplies" # Get these entries, but does not fail if not found properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status'] # Get a list of all Chassis and build URIs, then get all PowerSupplies # from each Power entry in the Chassis chassis_uri_list = self.chassis_uri_list for chassis_uri in chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Power' in data: power_uri = data[u'Power'][u'@odata.id'] else: continue response = self.get_request(self.root_uri + power_uri) data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} psu_list = data[key] for psu in psu_list: psu_not_present = False psu_data = {} for property in properties: if property in psu: if psu[property] is not None: if property == 'Status': if 'State' in psu[property]: if psu[property]['State'] == 'Absent': psu_not_present = True psu_data[property] = psu[property] if psu_not_present: continue psu_results.append(psu_data) result["entries"] = psu_results if not result["entries"]: return {'ret': False, 'msg': "No PowerSupply objects found"} return result def get_multi_psu_inventory(self): return self.aggregate(self.get_psu_inventory) def get_system_inventory(self, systems_uri): result = {} inventory = {} # Get these entries, but does not fail if not found properties = ['Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag', 'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary', 'ProcessorSummary', 'TrustedModules'] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for property in properties: if property in data: inventory[property] = data[property] result["entries"] = inventory return result def get_multi_system_inventory(self): return self.aggregate(self.get_system_inventory)
closed
ansible/ansible
https://github.com/ansible/ansible
63,803
Doc errors in aws_batch_job_queue
##### SUMMARY Documentation on `aws_batch_job_queue` has bugs: * module is `aws_batch_job_queue`, not `batch_job_queue` * the `batch_job_queue_action` variable is never registered * the `debug` task uses the old YAML style ##### ISSUE TYPE - Documentation Report ##### COMPONENT NAME `aws_batch_job_queue` ##### ANSIBLE VERSION ``` ansible 2.8.6 config file = None configured module search path = ['/home/major/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/major/.pyenv/versions/3.7.5/envs/venv-3.7.5/lib/python3.7/site-packages/ansible executable location = /home/major/.pyenv/versions/venv-3.7.5/bin/ansible python version = 3.7.5 (default, Oct 21 2019, 08:25:03) [GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] ``` ##### CONFIGURATION ``` [ no output ] ``` ##### OS / ENVIRONMENT Fedora 30 with Python 3.7.5 (from pyenv) ##### ADDITIONAL INFORMATION No extra information.
https://github.com/ansible/ansible/issues/63803
https://github.com/ansible/ansible/pull/63804
14eedb2956a304d582da63e57b7663c61eb7a7a4
4048fb4da72cd0ab132f66f5ecc7d45347861f40
2019-10-22T16:20:52Z
python
2019-10-29T14:24:21Z
lib/ansible/modules/cloud/amazon/aws_batch_job_queue.py
#!/usr/bin/python # Copyright (c) 2017 Jon Meran <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: aws_batch_job_queue short_description: Manage AWS Batch Job Queues description: - This module allows the management of AWS Batch Job Queues. It is idempotent and supports "Check" mode. Use module M(aws_batch_compute_environment) to manage the compute environment, M(aws_batch_job_queue) to manage job queues, M(aws_batch_job_definition) to manage job definitions. version_added: "2.5" author: Jon Meran (@jonmer85) options: job_queue_name: description: - The name for the job queue required: true state: description: - Describes the desired state. default: "present" choices: ["present", "absent"] job_queue_state: description: - The state of the job queue. If the job queue state is ENABLED , it is able to accept jobs. default: "ENABLED" choices: ["ENABLED", "DISABLED"] priority: description: - The priority of the job queue. Job queues with a higher priority (or a lower integer value for the priority parameter) are evaluated first when associated with same compute environment. Priority is determined in ascending order, for example, a job queue with a priority value of 1 is given scheduling preference over a job queue with a priority value of 10. required: true compute_environment_order: description: - The set of compute environments mapped to a job queue and their order relative to each other. The job scheduler uses this parameter to determine which compute environment should execute a given job. Compute environments must be in the VALID state before you can associate them with a job queue. You can associate up to 3 compute environments with a job queue. required: true requirements: - boto3 extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' --- - hosts: localhost gather_facts: no vars: state: present tasks: - name: My Batch Job Queue aws_batch_job_queue: job_queue_name: jobQueueName state: present region: us-east-1 job_queue_state: ENABLED priority: 1 compute_environment_order: - order: 1 compute_environment: my_compute_env1 - order: 2 compute_environment: my_compute_env2 register: batch_job_queue_action - name: show results debug: var: batch_job_queue_action ''' RETURN = ''' --- output: description: "returns what action was taken, whether something was changed, invocation and response" returned: always sample: batch_job_queue_action: updated changed: false response: job_queue_arn: "arn:aws:batch:...." job_queue_name: <name> priority: 1 state: DISABLED status: UPDATING status_reason: "JobQueue Healthy" type: dict ''' from ansible.module_utils._text import to_native from ansible.module_utils.aws.batch import AWSConnection, cc, set_api_params from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import ec2_argument_spec, get_aws_connection_info, boto3_conn, HAS_BOTO3 from ansible.module_utils.ec2 import camel_dict_to_snake_dict import re import traceback try: from botocore.exceptions import ClientError, ParamValidationError, MissingParametersError except ImportError: pass # Handled by HAS_BOTO3 # --------------------------------------------------------------------------------------------------- # # Helper Functions & classes # # --------------------------------------------------------------------------------------------------- def validate_params(module, aws): """ Performs basic parameter validation. :param module: :param aws: :return: """ return # --------------------------------------------------------------------------------------------------- # # Batch Job Queue functions # # --------------------------------------------------------------------------------------------------- def get_current_job_queue(module, connection): try: environments = connection.client().describe_job_queues( jobQueues=[module.params['job_queue_name']] ) return environments['jobQueues'][0] if len(environments['jobQueues']) > 0 else None except ClientError: return None def create_job_queue(module, aws): """ Adds a Batch job queue :param module: :param aws: :return: """ client = aws.client('batch') changed = False # set API parameters params = ('job_queue_name', 'priority') api_params = set_api_params(module, params) if module.params['job_queue_state'] is not None: api_params['state'] = module.params['job_queue_state'] api_params['computeEnvironmentOrder'] = get_compute_environment_order_list(module) try: if not module.check_mode: client.create_job_queue(**api_params) changed = True except (ClientError, ParamValidationError, MissingParametersError) as e: module.fail_json(msg='Error creating compute environment: {0}'.format(to_native(e)), exception=traceback.format_exc()) return changed def get_compute_environment_order_list(module): compute_environment_order_list = [] for ceo in module.params['compute_environment_order']: compute_environment_order_list.append(dict(order=ceo['order'], computeEnvironment=ceo['compute_environment'])) return compute_environment_order_list def remove_job_queue(module, aws): """ Remove a Batch job queue :param module: :param aws: :return: """ client = aws.client('batch') changed = False # set API parameters api_params = {'jobQueue': module.params['job_queue_name']} try: if not module.check_mode: client.delete_job_queue(**api_params) changed = True except (ClientError, ParamValidationError, MissingParametersError) as e: module.fail_json(msg='Error removing job queue: {0}'.format(to_native(e)), exception=traceback.format_exc()) return changed def manage_state(module, aws): changed = False current_state = 'absent' state = module.params['state'] job_queue_state = module.params['job_queue_state'] job_queue_name = module.params['job_queue_name'] priority = module.params['priority'] action_taken = 'none' response = None check_mode = module.check_mode # check if the job queue exists current_job_queue = get_current_job_queue(module, aws) if current_job_queue: current_state = 'present' if state == 'present': if current_state == 'present': updates = False # Update Batch Job Queue configuration job_kwargs = {'jobQueue': job_queue_name} # Update configuration if needed if job_queue_state and current_job_queue['state'] != job_queue_state: job_kwargs.update({'state': job_queue_state}) updates = True if priority is not None and current_job_queue['priority'] != priority: job_kwargs.update({'priority': priority}) updates = True new_compute_environment_order_list = get_compute_environment_order_list(module) if new_compute_environment_order_list != current_job_queue['computeEnvironmentOrder']: job_kwargs['computeEnvironmentOrder'] = new_compute_environment_order_list updates = True if updates: try: if not check_mode: aws.client().update_job_queue(**job_kwargs) changed = True action_taken = "updated" except (ParamValidationError, ClientError) as e: module.fail_json(msg="Unable to update job queue: {0}".format(to_native(e)), exception=traceback.format_exc()) else: # Create Job Queue changed = create_job_queue(module, aws) action_taken = 'added' # Describe job queue response = get_current_job_queue(module, aws) if not response: module.fail_json(msg='Unable to get job queue information after creating/updating') else: if current_state == 'present': # remove the Job Queue changed = remove_job_queue(module, aws) action_taken = 'deleted' return dict(changed=changed, batch_job_queue_action=action_taken, response=response) # --------------------------------------------------------------------------------------------------- # # MAIN # # --------------------------------------------------------------------------------------------------- def main(): """ Main entry point. :return dict: changed, batch_job_queue_action, response """ argument_spec = ec2_argument_spec() argument_spec.update( dict( state=dict(required=False, default='present', choices=['present', 'absent']), job_queue_name=dict(required=True), job_queue_state=dict(required=False, default='ENABLED', choices=['ENABLED', 'DISABLED']), priority=dict(type='int', required=True), compute_environment_order=dict(type='list', required=True), region=dict(aliases=['aws_region', 'ec2_region']) ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) # validate dependencies if not HAS_BOTO3: module.fail_json(msg='boto3 is required for this module.') aws = AWSConnection(module, ['batch']) validate_params(module, aws) results = manage_state(module, aws) module.exit_json(**camel_dict_to_snake_dict(results)) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,139
ACMEAccount.get_request does not fails and returns status -1 due to wrong .netrc permissions
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> I discovered an issue in the `ACMEAccount` `module_utils`. Due to wrong permissions on `.netrc` file, the `fetch_url` method returns status `-1`, which skip the error check and make function return as the call was successful. This breaks `ACMEDirectory.__init__`, that reports an error in the ACME directory: `ACME directory does not seem to follow protocol ACME v2` (the same would happen with ACME v1 directory). I was able to discover the issue by exploding the AnsiballZ, debugging [`ACMEAccount.get_request` method](https://github.com/ansible/ansible/blob/66de3d429f2454f8491f0633bf4298f3703c5db3/lib/ansible/module_utils/acme.py#L619) and discovering on line 657 the failing check: https://github.com/ansible/ansible/blob/66de3d429f2454f8491f0633bf4298f3703c5db3/lib/ansible/module_utils/acme.py#L657 In this error case, the `info` dictionary had `status` value of `-1`: ``` { "url": "https: //acme-v02.api.letsencrypt.org/directory", "status": -1, "msg": "An unknown error occurred: ~/.netrc access too permissive: access permissions must restrict access to only the owner (/home/.../.netrc, line 3)", "exception": "Traceback (most recent call last): File "/home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/debug_dir/ansible/module_utils/urls.py", line 1359, in fetch_url unix_socket=unix_socket) File "/home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/debug_dir/ansible/module_utils/urls.py", line 1257, in open_url use_gssapi=use_gssapi, unix_socket=unix_socket) File "/home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/debug_dir/ansible/module_utils/urls.py", line 1090, in open rc = netrc.netrc(os.environ.get(\"NETRC\")) File "/home/.../.asdf/installs/python/3.7.2/lib/python3.7/netrc.py", line 30, in __init__ self._parse(file, fp, default_netrc) File "/home/.../.asdf/installs/python/3.7.2/lib/python3.7/netrc.py", line 107, in _parse " the owner", file, lexer.lineno) netrc.NetrcParseError: ~/.netrc access too permissive: access permissions must restrict access to only the owner (/home/.../.netrc, line 3) " } ``` This value is not intercepted by the error check, which expect failures to have status greater than 400. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> - `module_utils/acme.py` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = /home/etenani/code/github.com/bcmi-labs/operations/ansible.cfg configured module search path = [u'/home/etenani/code/github.com/bcmi-labs/operations/modules'] ansible python module location = /home/etenani/.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible executable location = /home/etenani/.local/share/virtualenvs/operations--a04GZk3/bin/ansible python version = 2.7.16 (default, Sep 3 2019, 16:43:55) [GCC 5.4.0 20160609] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below DEFAULT_ACTION_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/action', u'/usr/share/ansible/plugins/action'] DEFAULT_CACHE_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/cache', u'/usr/share/ansible/plugins/cache'] DEFAULT_CALLBACK_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/callback', u'/usr/share/ansible/plugins/callback'] DEFAULT_CONNECTION_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/connection', u'/usr/share/ansible/plugins/connection'] DEFAULT_FILTER_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/filter', u'/usr/share/ansible/plugins/filter'] DEFAULT_GATHERING(/home/.../operations/ansible.cfg) = smart DEFAULT_INVENTORY_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/inventory', u'/usr/share/ansible/plugins/inventory'] DEFAULT_KEEP_REMOTE_FILES(env: ANSIBLE_KEEP_REMOTE_FILES) = True DEFAULT_LOOKUP_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/lookup', u'/usr/share/ansible/plugins/lookup'] DEFAULT_MODULE_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/modules'] DEFAULT_MODULE_UTILS_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/modules/utils'] DEFAULT_REMOTE_USER(/home/.../operations/ansible.cfg) = ansible DEFAULT_ROLES_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/roles/community', u'/home/.../operations/roles'] DEFAULT_STRATEGY_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/strategy', u'/usr/share/ansible/plugins/strategy'] DEFAULT_TERMINAL_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/terminal', u'/usr/share/ansible/plugins/terminal'] DEFAULT_TEST_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/test', u'/usr/share/ansible/plugins/test'] DEFAULT_VARS_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/vars', u'/usr/share/ansible/plugins/vars'] HOST_KEY_CHECKING(/home/.../operations/ansible.cfg) = False INJECT_FACTS_AS_VARS(/home/.../operations/ansible.cfg) = True RETRY_FILES_ENABLED(/home/.../operations/ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> - Python 2.7.16 - OS Distributor ID: Ubuntu Description: Ubuntu 18.04.2 LTS Release: 18.04 Codename: bionic ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> - create `$HOME/.netrc` - set permissive permissions: `chmod 664 $HOME/.netrc` - run `acme_account` module <!--- Paste example playbooks or commands between quotes below --> ```yaml # example task - name: ACME account acme_account: state: present terms_agreed: true acme_directory: "{{ acme_parameters.directory }}" acme_version: "{{ acme_parameters.version }}" account_key_content: "{{ acme_account_key }}" contact: - "{{ acme_parameters.account_email }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> I would expect the task to produce a clear error related to the problematic situation. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The task errors with an error related to the ACME directory being interrogated not supporting the ACME protocol. This is the task output (with `-vvvv`): ``` TASK [tls-certificates : ACME account] ******************************************************************************************************************************************************************************************************** task path: /home/.../operations/roles/tls-certificates/tasks/main.yml:4 File lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/account.json as file Sops lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/[email protected] as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: etenani <127.0.0.1> EXEC /bin/sh -c 'echo ~etenani && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" && echo ansible-tmp-1570199461.7-3341753761542="` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" ) && sleep 0' Using module file /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/modules/crypto/acme/acme_account.py <127.0.0.1> PUT /home/.../.ansible/tmp/ansible-local-2816937gtWS/tmp07AMHJ TO /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/ /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/home/.../.local/share/virtualenvs/operations--a04GZk3/bin/python2.7 /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' The full traceback is: WARNING: The below traceback may *not* be related to the actual failure. File "/tmp/ansible_acme_account_payload_CdfMSZ/__main__.py", line 180, in main account = ACMEAccount(module) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 500, in __init__ self.directory = ACMEDirectory(module, self) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 452, in __init__ raise ModuleFailException("ACME directory does not seem to follow protocol ACME v2") fatal: [localhost]: FAILED! => { "changed": false, "invocation": { "module_args": { "account_key_content": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "account_key_src": null, "account_uri": null, "acme_directory": "https://acme-v02.api.letsencrypt.org/directory", "acme_version": 2, "allow_creation": true, "contact": [ "REDACTED" ], "new_account_key_content": null, "new_account_key_src": null, "select_crypto_backend": "auto", "state": "present", "terms_agreed": true, "validate_certs": true } }, "msg": "ACME directory does not seem to follow protocol ACME v2", "other": {} } ``` <!--- Paste verbatim command output between quotes --> <details> <summary>Full output</summary> ``` ansible-playbook 2.8.5 config file = /home/.../operations/ansible.cfg configured module search path = [u'/home/.../operations/modules'] ansible python module location = /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible executable location = /home/.../.local/share/virtualenvs/operations--a04GZk3/bin/ansible-playbook python version = 2.7.16 (default, Sep 3 2019, 16:43:55) [GCC 5.4.0 20160609] Using /home/.../operations/ansible.cfg as config file setting up inventory plugins host_list declined parsing /home/.../operations/inventories/prod/hosts as it did not pass it's verify_file() method Not replacing invalid character(s) "set([u'-'])" in group name (us-east-1) [DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters in group names by default, this will change, but still be user configurable on deprecation. This feature will be removed in version 2.10. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. [WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details Parsed /home/.../operations/inventories/prod/hosts inventory source with script plugin statically imported: /home/.../operations/roles/community/datadog/tasks/pkg-debian.yml statically imported: /home/.../operations/roles/community/datadog/tasks/pkg-redhat.yml statically imported: /home/.../operations/roles/community/datadog/tasks/pkg-suse.yml statically imported: /home/.../operations/roles/community/datadog/tasks/agent5.yml statically imported: /home/.../operations/roles/community/datadog/tasks/agent6.yml Loading callback plugin default of type stdout, v2.0 from /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/plugins/callback/default.pyc Loading callback plugin human_log of type notification, v2.0 from /home/.../operations/plugins/callback/human-stderr.pyc PLAYBOOK: tower-certificates.yaml ************************************************************************************************************************************************************************************************************* Positional arguments: playbooks/tower-certificates.yaml remote_user: ansible become_method: sudo inventory: (u'/home/.../operations/inventories/prod/hosts',) forks: 5 tags: (u'all',) verbosity: 4 connection: smart timeout: 10 6 plays in playbooks/tower-certificates.yaml PLAY [localhost] ****************************************************************************************************************************************************************************************************************************** key: all./home/.../operations/inventories/prod/group_vars key: all./home/.../operations/playbooks/group_vars key: localhost./home/.../operations/inventories/prod/host_vars key: localhost./home/.../operations/playbooks/host_vars TASK [Gathering Facts] ************************************************************************************************************************************************************************************************************************ task path: /home/.../operations/playbooks/tower-certificates.yaml:5 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: etenani <127.0.0.1> EXEC /bin/sh -c 'echo ~etenani && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112 `" && echo ansible-tmp-1570199460.06-148859103532112="` echo /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112 `" ) && sleep 0' Using module file /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/modules/system/setup.py <127.0.0.1> PUT /home/.../.ansible/tmp/ansible-local-2816937gtWS/tmp2OAzkM TO /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/AnsiballZ_setup.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/ /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/home/.../.local/share/virtualenvs/operations--a04GZk3/bin/python2.7 /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/AnsiballZ_setup.py && sleep 0' ok: [localhost] META: ran handlers key: all./home/.../operations/inventories/prod/group_vars key: all./home/.../operations/playbooks/group_vars key: localhost./home/.../operations/inventories/prod/host_vars key: localhost./home/.../operations/playbooks/host_vars TASK [tls-certificates : ACME account] ******************************************************************************************************************************************************************************************************** task path: /home/.../operations/roles/tls-certificates/tasks/main.yml:4 File lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/account.json as file Sops lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/[email protected] as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: etenani <127.0.0.1> EXEC /bin/sh -c 'echo ~etenani && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" && echo ansible-tmp-1570199461.7-3341753761542="` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" ) && sleep 0' Using module file /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/modules/crypto/acme/acme_account.py <127.0.0.1> PUT /home/.../.ansible/tmp/ansible-local-2816937gtWS/tmp07AMHJ TO /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/ /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/home/.../.local/share/virtualenvs/operations--a04GZk3/bin/python2.7 /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' The full traceback is: WARNING: The below traceback may *not* be related to the actual failure. File "/tmp/ansible_acme_account_payload_CdfMSZ/__main__.py", line 180, in main account = ACMEAccount(module) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 500, in __init__ self.directory = ACMEDirectory(module, self) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 452, in __init__ raise ModuleFailException("ACME directory does not seem to follow protocol ACME v2") fatal: [localhost]: FAILED! => { "changed": false, "invocation": { "module_args": { "account_key_content": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "account_key_src": null, "account_uri": null, "acme_directory": "https://acme-v02.api.letsencrypt.org/directory", "acme_version": 2, "allow_creation": true, "contact": [ "REDACTED" ], "new_account_key_content": null, "new_account_key_src": null, "select_crypto_backend": "auto", "state": "present", "terms_agreed": true, "validate_certs": true } }, "msg": "ACME directory does not seem to follow protocol ACME v2", "other": {} } PLAY RECAP ************************************************************************************************************************************************************************************************************************************ localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ``` </details>
https://github.com/ansible/ansible/issues/63139
https://github.com/ansible/ansible/pull/63140
c782831dd7de046e369107a553c400e7cbce5a11
0d905a0496f4554a9de57cbd3ee90e30d6249b34
2019-10-04T15:42:14Z
python
2019-10-29T18:44:25Z
changelogs/fragments/63140-acme-fix-fetch-url-status-codes.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
63,139
ACMEAccount.get_request does not fails and returns status -1 due to wrong .netrc permissions
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> I discovered an issue in the `ACMEAccount` `module_utils`. Due to wrong permissions on `.netrc` file, the `fetch_url` method returns status `-1`, which skip the error check and make function return as the call was successful. This breaks `ACMEDirectory.__init__`, that reports an error in the ACME directory: `ACME directory does not seem to follow protocol ACME v2` (the same would happen with ACME v1 directory). I was able to discover the issue by exploding the AnsiballZ, debugging [`ACMEAccount.get_request` method](https://github.com/ansible/ansible/blob/66de3d429f2454f8491f0633bf4298f3703c5db3/lib/ansible/module_utils/acme.py#L619) and discovering on line 657 the failing check: https://github.com/ansible/ansible/blob/66de3d429f2454f8491f0633bf4298f3703c5db3/lib/ansible/module_utils/acme.py#L657 In this error case, the `info` dictionary had `status` value of `-1`: ``` { "url": "https: //acme-v02.api.letsencrypt.org/directory", "status": -1, "msg": "An unknown error occurred: ~/.netrc access too permissive: access permissions must restrict access to only the owner (/home/.../.netrc, line 3)", "exception": "Traceback (most recent call last): File "/home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/debug_dir/ansible/module_utils/urls.py", line 1359, in fetch_url unix_socket=unix_socket) File "/home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/debug_dir/ansible/module_utils/urls.py", line 1257, in open_url use_gssapi=use_gssapi, unix_socket=unix_socket) File "/home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/debug_dir/ansible/module_utils/urls.py", line 1090, in open rc = netrc.netrc(os.environ.get(\"NETRC\")) File "/home/.../.asdf/installs/python/3.7.2/lib/python3.7/netrc.py", line 30, in __init__ self._parse(file, fp, default_netrc) File "/home/.../.asdf/installs/python/3.7.2/lib/python3.7/netrc.py", line 107, in _parse " the owner", file, lexer.lineno) netrc.NetrcParseError: ~/.netrc access too permissive: access permissions must restrict access to only the owner (/home/.../.netrc, line 3) " } ``` This value is not intercepted by the error check, which expect failures to have status greater than 400. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> - `module_utils/acme.py` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = /home/etenani/code/github.com/bcmi-labs/operations/ansible.cfg configured module search path = [u'/home/etenani/code/github.com/bcmi-labs/operations/modules'] ansible python module location = /home/etenani/.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible executable location = /home/etenani/.local/share/virtualenvs/operations--a04GZk3/bin/ansible python version = 2.7.16 (default, Sep 3 2019, 16:43:55) [GCC 5.4.0 20160609] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below DEFAULT_ACTION_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/action', u'/usr/share/ansible/plugins/action'] DEFAULT_CACHE_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/cache', u'/usr/share/ansible/plugins/cache'] DEFAULT_CALLBACK_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/callback', u'/usr/share/ansible/plugins/callback'] DEFAULT_CONNECTION_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/connection', u'/usr/share/ansible/plugins/connection'] DEFAULT_FILTER_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/filter', u'/usr/share/ansible/plugins/filter'] DEFAULT_GATHERING(/home/.../operations/ansible.cfg) = smart DEFAULT_INVENTORY_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/inventory', u'/usr/share/ansible/plugins/inventory'] DEFAULT_KEEP_REMOTE_FILES(env: ANSIBLE_KEEP_REMOTE_FILES) = True DEFAULT_LOOKUP_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/lookup', u'/usr/share/ansible/plugins/lookup'] DEFAULT_MODULE_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/modules'] DEFAULT_MODULE_UTILS_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/modules/utils'] DEFAULT_REMOTE_USER(/home/.../operations/ansible.cfg) = ansible DEFAULT_ROLES_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/roles/community', u'/home/.../operations/roles'] DEFAULT_STRATEGY_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/strategy', u'/usr/share/ansible/plugins/strategy'] DEFAULT_TERMINAL_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/terminal', u'/usr/share/ansible/plugins/terminal'] DEFAULT_TEST_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/test', u'/usr/share/ansible/plugins/test'] DEFAULT_VARS_PLUGIN_PATH(/home/.../operations/ansible.cfg) = [u'/home/.../operations/plugins/vars', u'/usr/share/ansible/plugins/vars'] HOST_KEY_CHECKING(/home/.../operations/ansible.cfg) = False INJECT_FACTS_AS_VARS(/home/.../operations/ansible.cfg) = True RETRY_FILES_ENABLED(/home/.../operations/ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> - Python 2.7.16 - OS Distributor ID: Ubuntu Description: Ubuntu 18.04.2 LTS Release: 18.04 Codename: bionic ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> - create `$HOME/.netrc` - set permissive permissions: `chmod 664 $HOME/.netrc` - run `acme_account` module <!--- Paste example playbooks or commands between quotes below --> ```yaml # example task - name: ACME account acme_account: state: present terms_agreed: true acme_directory: "{{ acme_parameters.directory }}" acme_version: "{{ acme_parameters.version }}" account_key_content: "{{ acme_account_key }}" contact: - "{{ acme_parameters.account_email }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> I would expect the task to produce a clear error related to the problematic situation. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> The task errors with an error related to the ACME directory being interrogated not supporting the ACME protocol. This is the task output (with `-vvvv`): ``` TASK [tls-certificates : ACME account] ******************************************************************************************************************************************************************************************************** task path: /home/.../operations/roles/tls-certificates/tasks/main.yml:4 File lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/account.json as file Sops lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/[email protected] as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: etenani <127.0.0.1> EXEC /bin/sh -c 'echo ~etenani && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" && echo ansible-tmp-1570199461.7-3341753761542="` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" ) && sleep 0' Using module file /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/modules/crypto/acme/acme_account.py <127.0.0.1> PUT /home/.../.ansible/tmp/ansible-local-2816937gtWS/tmp07AMHJ TO /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/ /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/home/.../.local/share/virtualenvs/operations--a04GZk3/bin/python2.7 /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' The full traceback is: WARNING: The below traceback may *not* be related to the actual failure. File "/tmp/ansible_acme_account_payload_CdfMSZ/__main__.py", line 180, in main account = ACMEAccount(module) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 500, in __init__ self.directory = ACMEDirectory(module, self) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 452, in __init__ raise ModuleFailException("ACME directory does not seem to follow protocol ACME v2") fatal: [localhost]: FAILED! => { "changed": false, "invocation": { "module_args": { "account_key_content": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "account_key_src": null, "account_uri": null, "acme_directory": "https://acme-v02.api.letsencrypt.org/directory", "acme_version": 2, "allow_creation": true, "contact": [ "REDACTED" ], "new_account_key_content": null, "new_account_key_src": null, "select_crypto_backend": "auto", "state": "present", "terms_agreed": true, "validate_certs": true } }, "msg": "ACME directory does not seem to follow protocol ACME v2", "other": {} } ``` <!--- Paste verbatim command output between quotes --> <details> <summary>Full output</summary> ``` ansible-playbook 2.8.5 config file = /home/.../operations/ansible.cfg configured module search path = [u'/home/.../operations/modules'] ansible python module location = /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible executable location = /home/.../.local/share/virtualenvs/operations--a04GZk3/bin/ansible-playbook python version = 2.7.16 (default, Sep 3 2019, 16:43:55) [GCC 5.4.0 20160609] Using /home/.../operations/ansible.cfg as config file setting up inventory plugins host_list declined parsing /home/.../operations/inventories/prod/hosts as it did not pass it's verify_file() method Not replacing invalid character(s) "set([u'-'])" in group name (us-east-1) [DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters in group names by default, this will change, but still be user configurable on deprecation. This feature will be removed in version 2.10. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. [WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details Parsed /home/.../operations/inventories/prod/hosts inventory source with script plugin statically imported: /home/.../operations/roles/community/datadog/tasks/pkg-debian.yml statically imported: /home/.../operations/roles/community/datadog/tasks/pkg-redhat.yml statically imported: /home/.../operations/roles/community/datadog/tasks/pkg-suse.yml statically imported: /home/.../operations/roles/community/datadog/tasks/agent5.yml statically imported: /home/.../operations/roles/community/datadog/tasks/agent6.yml Loading callback plugin default of type stdout, v2.0 from /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/plugins/callback/default.pyc Loading callback plugin human_log of type notification, v2.0 from /home/.../operations/plugins/callback/human-stderr.pyc PLAYBOOK: tower-certificates.yaml ************************************************************************************************************************************************************************************************************* Positional arguments: playbooks/tower-certificates.yaml remote_user: ansible become_method: sudo inventory: (u'/home/.../operations/inventories/prod/hosts',) forks: 5 tags: (u'all',) verbosity: 4 connection: smart timeout: 10 6 plays in playbooks/tower-certificates.yaml PLAY [localhost] ****************************************************************************************************************************************************************************************************************************** key: all./home/.../operations/inventories/prod/group_vars key: all./home/.../operations/playbooks/group_vars key: localhost./home/.../operations/inventories/prod/host_vars key: localhost./home/.../operations/playbooks/host_vars TASK [Gathering Facts] ************************************************************************************************************************************************************************************************************************ task path: /home/.../operations/playbooks/tower-certificates.yaml:5 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: etenani <127.0.0.1> EXEC /bin/sh -c 'echo ~etenani && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112 `" && echo ansible-tmp-1570199460.06-148859103532112="` echo /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112 `" ) && sleep 0' Using module file /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/modules/system/setup.py <127.0.0.1> PUT /home/.../.ansible/tmp/ansible-local-2816937gtWS/tmp2OAzkM TO /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/AnsiballZ_setup.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/ /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/AnsiballZ_setup.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/home/.../.local/share/virtualenvs/operations--a04GZk3/bin/python2.7 /home/.../.ansible/tmp/ansible-tmp-1570199460.06-148859103532112/AnsiballZ_setup.py && sleep 0' ok: [localhost] META: ran handlers key: all./home/.../operations/inventories/prod/group_vars key: all./home/.../operations/playbooks/group_vars key: localhost./home/.../operations/inventories/prod/host_vars key: localhost./home/.../operations/playbooks/host_vars TASK [tls-certificates : ACME account] ******************************************************************************************************************************************************************************************************** task path: /home/.../operations/roles/tls-certificates/tasks/main.yml:4 File lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/account.json as file Sops lookup using /home/.../operations/roles/tls-certificates/files/accounts/acme-v02.api.letsencrypt.org/[email protected]/[email protected] as file <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: etenani <127.0.0.1> EXEC /bin/sh -c 'echo ~etenani && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" && echo ansible-tmp-1570199461.7-3341753761542="` echo /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542 `" ) && sleep 0' Using module file /home/.../.local/share/virtualenvs/operations--a04GZk3/lib/python2.7/site-packages/ansible/modules/crypto/acme/acme_account.py <127.0.0.1> PUT /home/.../.ansible/tmp/ansible-local-2816937gtWS/tmp07AMHJ TO /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/ /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/home/.../.local/share/virtualenvs/operations--a04GZk3/bin/python2.7 /home/.../.ansible/tmp/ansible-tmp-1570199461.7-3341753761542/AnsiballZ_acme_account.py && sleep 0' The full traceback is: WARNING: The below traceback may *not* be related to the actual failure. File "/tmp/ansible_acme_account_payload_CdfMSZ/__main__.py", line 180, in main account = ACMEAccount(module) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 500, in __init__ self.directory = ACMEDirectory(module, self) File "/tmp/ansible_acme_account_payload_CdfMSZ/ansible_acme_account_payload.zip/ansible/module_utils/acme.py", line 452, in __init__ raise ModuleFailException("ACME directory does not seem to follow protocol ACME v2") fatal: [localhost]: FAILED! => { "changed": false, "invocation": { "module_args": { "account_key_content": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "account_key_src": null, "account_uri": null, "acme_directory": "https://acme-v02.api.letsencrypt.org/directory", "acme_version": 2, "allow_creation": true, "contact": [ "REDACTED" ], "new_account_key_content": null, "new_account_key_src": null, "select_crypto_backend": "auto", "state": "present", "terms_agreed": true, "validate_certs": true } }, "msg": "ACME directory does not seem to follow protocol ACME v2", "other": {} } PLAY RECAP ************************************************************************************************************************************************************************************************************************************ localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ``` </details>
https://github.com/ansible/ansible/issues/63139
https://github.com/ansible/ansible/pull/63140
c782831dd7de046e369107a553c400e7cbce5a11
0d905a0496f4554a9de57cbd3ee90e30d6249b34
2019-10-04T15:42:14Z
python
2019-10-29T18:44:25Z
lib/ansible/module_utils/acme.py
# -*- coding: utf-8 -*- # This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c), Michael Gruener <[email protected]>, 2016 # # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function __metaclass__ = type import base64 import binascii import copy import datetime import hashlib import json import locale import os import re import shutil import sys import tempfile import traceback from ansible.module_utils.basic import missing_required_lib from ansible.module_utils._text import to_native, to_text, to_bytes from ansible.module_utils.urls import fetch_url from ansible.module_utils.compat import ipaddress as compat_ipaddress from ansible.module_utils.six.moves.urllib.parse import unquote try: import cryptography import cryptography.hazmat.backends import cryptography.hazmat.primitives.serialization import cryptography.hazmat.primitives.asymmetric.rsa import cryptography.hazmat.primitives.asymmetric.ec import cryptography.hazmat.primitives.asymmetric.padding import cryptography.hazmat.primitives.hashes import cryptography.hazmat.primitives.asymmetric.utils import cryptography.x509 import cryptography.x509.oid from distutils.version import LooseVersion CRYPTOGRAPHY_VERSION = cryptography.__version__ HAS_CURRENT_CRYPTOGRAPHY = (LooseVersion(CRYPTOGRAPHY_VERSION) >= LooseVersion('1.5')) if HAS_CURRENT_CRYPTOGRAPHY: _cryptography_backend = cryptography.hazmat.backends.default_backend() except Exception as dummy: HAS_CURRENT_CRYPTOGRAPHY = False class ModuleFailException(Exception): ''' If raised, module.fail_json() will be called with the given parameters after cleanup. ''' def __init__(self, msg, **args): super(ModuleFailException, self).__init__(self, msg) self.msg = msg self.module_fail_args = args def do_fail(self, module, **arguments): module.fail_json(msg=self.msg, other=self.module_fail_args, **arguments) def nopad_b64(data): return base64.urlsafe_b64encode(data).decode('utf8').replace("=", "") def read_file(fn, mode='b'): try: with open(fn, 'r' + mode) as f: return f.read() except Exception as e: raise ModuleFailException('Error while reading file "{0}": {1}'.format(fn, e)) # function source: network/basics/uri.py def write_file(module, dest, content): ''' Write content to destination file dest, only if the content has changed. ''' changed = False # create a tempfile fd, tmpsrc = tempfile.mkstemp(text=False) f = os.fdopen(fd, 'wb') try: f.write(content) except Exception as err: try: f.close() except Exception as dummy: pass os.remove(tmpsrc) raise ModuleFailException("failed to create temporary content file: %s" % to_native(err), exception=traceback.format_exc()) f.close() checksum_src = None checksum_dest = None # raise an error if there is no tmpsrc file if not os.path.exists(tmpsrc): try: os.remove(tmpsrc) except Exception as dummy: pass raise ModuleFailException("Source %s does not exist" % (tmpsrc)) if not os.access(tmpsrc, os.R_OK): os.remove(tmpsrc) raise ModuleFailException("Source %s not readable" % (tmpsrc)) checksum_src = module.sha1(tmpsrc) # check if there is no dest file if os.path.exists(dest): # raise an error if copy has no permission on dest if not os.access(dest, os.W_OK): os.remove(tmpsrc) raise ModuleFailException("Destination %s not writable" % (dest)) if not os.access(dest, os.R_OK): os.remove(tmpsrc) raise ModuleFailException("Destination %s not readable" % (dest)) checksum_dest = module.sha1(dest) else: dirname = os.path.dirname(dest) or '.' if not os.access(dirname, os.W_OK): os.remove(tmpsrc) raise ModuleFailException("Destination dir %s not writable" % (dirname)) if checksum_src != checksum_dest: try: shutil.copyfile(tmpsrc, dest) changed = True except Exception as err: os.remove(tmpsrc) raise ModuleFailException("failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(err)), exception=traceback.format_exc()) os.remove(tmpsrc) return changed def pem_to_der(pem_filename): ''' Load PEM file, and convert to DER. If PEM contains multiple entities, the first entity will be used. ''' certificate_lines = [] try: with open(pem_filename, "rt") as f: header_line_count = 0 for line in f: if line.startswith('-----'): header_line_count += 1 if header_line_count == 2: # If certificate file contains other certs appended # (like intermediate certificates), ignore these. break continue certificate_lines.append(line.strip()) except Exception as err: raise ModuleFailException("cannot load PEM file {0}: {1}".format(pem_filename, to_native(err)), exception=traceback.format_exc()) return base64.b64decode(''.join(certificate_lines)) def _parse_key_openssl(openssl_binary, module, key_file=None, key_content=None): ''' Parses an RSA or Elliptic Curve key file in PEM format and returns a pair (error, key_data). ''' # If key_file isn't given, but key_content, write that to a temporary file if key_file is None: fd, tmpsrc = tempfile.mkstemp() module.add_cleanup_file(tmpsrc) # Ansible will delete the file on exit f = os.fdopen(fd, 'wb') try: f.write(key_content.encode('utf-8')) key_file = tmpsrc except Exception as err: try: f.close() except Exception as dummy: pass raise ModuleFailException("failed to create temporary content file: %s" % to_native(err), exception=traceback.format_exc()) f.close() # Parse key account_key_type = None with open(key_file, "rt") as f: for line in f: m = re.match(r"^\s*-{5,}BEGIN\s+(EC|RSA)\s+PRIVATE\s+KEY-{5,}\s*$", line) if m is not None: account_key_type = m.group(1).lower() break if account_key_type is None: # This happens for example if openssl_privatekey created this key # (as opposed to the OpenSSL binary). For now, we assume this is # an RSA key. # FIXME: add some kind of auto-detection account_key_type = "rsa" if account_key_type not in ("rsa", "ec"): return 'unknown key type "%s"' % account_key_type, {} openssl_keydump_cmd = [openssl_binary, account_key_type, "-in", key_file, "-noout", "-text"] dummy, out, dummy = module.run_command(openssl_keydump_cmd, check_rc=True) if account_key_type == 'rsa': pub_hex, pub_exp = re.search( r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)", to_text(out, errors='surrogate_or_strict'), re.MULTILINE | re.DOTALL).groups() pub_exp = "{0:x}".format(int(pub_exp)) if len(pub_exp) % 2: pub_exp = "0{0}".format(pub_exp) return None, { 'key_file': key_file, 'type': 'rsa', 'alg': 'RS256', 'jwk': { "kty": "RSA", "e": nopad_b64(binascii.unhexlify(pub_exp.encode("utf-8"))), "n": nopad_b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))), }, 'hash': 'sha256', } elif account_key_type == 'ec': pub_data = re.search( r"pub:\s*\n\s+04:([a-f0-9\:\s]+?)\nASN1 OID: (\S+)(?:\nNIST CURVE: (\S+))?", to_text(out, errors='surrogate_or_strict'), re.MULTILINE | re.DOTALL) if pub_data is None: return 'cannot parse elliptic curve key', {} pub_hex = binascii.unhexlify(re.sub(r"(\s|:)", "", pub_data.group(1)).encode("utf-8")) asn1_oid_curve = pub_data.group(2).lower() nist_curve = pub_data.group(3).lower() if pub_data.group(3) else None if asn1_oid_curve == 'prime256v1' or nist_curve == 'p-256': bits = 256 alg = 'ES256' hashalg = 'sha256' point_size = 32 curve = 'P-256' elif asn1_oid_curve == 'secp384r1' or nist_curve == 'p-384': bits = 384 alg = 'ES384' hashalg = 'sha384' point_size = 48 curve = 'P-384' elif asn1_oid_curve == 'secp521r1' or nist_curve == 'p-521': # Not yet supported on Let's Encrypt side, see # https://github.com/letsencrypt/boulder/issues/2217 bits = 521 alg = 'ES512' hashalg = 'sha512' point_size = 66 curve = 'P-521' else: return 'unknown elliptic curve: %s / %s' % (asn1_oid_curve, nist_curve), {} num_bytes = (bits + 7) // 8 if len(pub_hex) != 2 * num_bytes: return 'bad elliptic curve point (%s / %s)' % (asn1_oid_curve, nist_curve), {} return None, { 'key_file': key_file, 'type': 'ec', 'alg': alg, 'jwk': { "kty": "EC", "crv": curve, "x": nopad_b64(pub_hex[:num_bytes]), "y": nopad_b64(pub_hex[num_bytes:]), }, 'hash': hashalg, 'point_size': point_size, } def _sign_request_openssl(openssl_binary, module, payload64, protected64, key_data): openssl_sign_cmd = [openssl_binary, "dgst", "-{0}".format(key_data['hash']), "-sign", key_data['key_file']] sign_payload = "{0}.{1}".format(protected64, payload64).encode('utf8') dummy, out, dummy = module.run_command(openssl_sign_cmd, data=sign_payload, check_rc=True, binary_data=True) if key_data['type'] == 'ec': dummy, der_out, dummy = module.run_command( [openssl_binary, "asn1parse", "-inform", "DER"], data=out, binary_data=True) expected_len = 2 * key_data['point_size'] sig = re.findall( r"prim:\s+INTEGER\s+:([0-9A-F]{1,%s})\n" % expected_len, to_text(der_out, errors='surrogate_or_strict')) if len(sig) != 2: raise ModuleFailException( "failed to generate Elliptic Curve signature; cannot parse DER output: {0}".format( to_text(der_out, errors='surrogate_or_strict'))) sig[0] = (expected_len - len(sig[0])) * '0' + sig[0] sig[1] = (expected_len - len(sig[1])) * '0' + sig[1] out = binascii.unhexlify(sig[0]) + binascii.unhexlify(sig[1]) return { "protected": protected64, "payload": payload64, "signature": nopad_b64(to_bytes(out)), } if sys.version_info[0] >= 3: # Python 3 (and newer) def _count_bytes(n): return (n.bit_length() + 7) // 8 if n > 0 else 0 def _convert_int_to_bytes(count, no): return no.to_bytes(count, byteorder='big') def _pad_hex(n, digits): res = hex(n)[2:] if len(res) < digits: res = '0' * (digits - len(res)) + res return res else: # Python 2 def _count_bytes(n): if n <= 0: return 0 h = '%x' % n return (len(h) + 1) // 2 def _convert_int_to_bytes(count, n): h = '%x' % n if len(h) > 2 * count: raise Exception('Number {1} needs more than {0} bytes!'.format(count, n)) return ('0' * (2 * count - len(h)) + h).decode('hex') def _pad_hex(n, digits): h = '%x' % n if len(h) < digits: h = '0' * (digits - len(h)) + h return h def _parse_key_cryptography(module, key_file=None, key_content=None): ''' Parses an RSA or Elliptic Curve key file in PEM format and returns a pair (error, key_data). ''' # If key_content isn't given, read key_file if key_content is None: key_content = read_file(key_file) else: key_content = to_bytes(key_content) # Parse key try: key = cryptography.hazmat.primitives.serialization.load_pem_private_key(key_content, password=None, backend=_cryptography_backend) except Exception as e: return 'error while loading key: {0}'.format(e), None if isinstance(key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey): pk = key.public_key().public_numbers() return None, { 'key_obj': key, 'type': 'rsa', 'alg': 'RS256', 'jwk': { "kty": "RSA", "e": nopad_b64(_convert_int_to_bytes(_count_bytes(pk.e), pk.e)), "n": nopad_b64(_convert_int_to_bytes(_count_bytes(pk.n), pk.n)), }, 'hash': 'sha256', } elif isinstance(key, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey): pk = key.public_key().public_numbers() if pk.curve.name == 'secp256r1': bits = 256 alg = 'ES256' hashalg = 'sha256' point_size = 32 curve = 'P-256' elif pk.curve.name == 'secp384r1': bits = 384 alg = 'ES384' hashalg = 'sha384' point_size = 48 curve = 'P-384' elif pk.curve.name == 'secp521r1': # Not yet supported on Let's Encrypt side, see # https://github.com/letsencrypt/boulder/issues/2217 bits = 521 alg = 'ES512' hashalg = 'sha512' point_size = 66 curve = 'P-521' else: return 'unknown elliptic curve: {0}'.format(pk.curve.name), {} num_bytes = (bits + 7) // 8 return None, { 'key_obj': key, 'type': 'ec', 'alg': alg, 'jwk': { "kty": "EC", "crv": curve, "x": nopad_b64(_convert_int_to_bytes(num_bytes, pk.x)), "y": nopad_b64(_convert_int_to_bytes(num_bytes, pk.y)), }, 'hash': hashalg, 'point_size': point_size, } else: return 'unknown key type "{0}"'.format(type(key)), {} def _sign_request_cryptography(module, payload64, protected64, key_data): sign_payload = "{0}.{1}".format(protected64, payload64).encode('utf8') if isinstance(key_data['key_obj'], cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey): padding = cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15() hashalg = cryptography.hazmat.primitives.hashes.SHA256 signature = key_data['key_obj'].sign(sign_payload, padding, hashalg()) elif isinstance(key_data['key_obj'], cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey): if key_data['hash'] == 'sha256': hashalg = cryptography.hazmat.primitives.hashes.SHA256 elif key_data['hash'] == 'sha384': hashalg = cryptography.hazmat.primitives.hashes.SHA384 elif key_data['hash'] == 'sha512': hashalg = cryptography.hazmat.primitives.hashes.SHA512 ecdsa = cryptography.hazmat.primitives.asymmetric.ec.ECDSA(hashalg()) r, s = cryptography.hazmat.primitives.asymmetric.utils.decode_dss_signature(key_data['key_obj'].sign(sign_payload, ecdsa)) rr = _pad_hex(r, 2 * key_data['point_size']) ss = _pad_hex(s, 2 * key_data['point_size']) signature = binascii.unhexlify(rr) + binascii.unhexlify(ss) return { "protected": protected64, "payload": payload64, "signature": nopad_b64(signature), } class ACMEDirectory(object): ''' The ACME server directory. Gives access to the available resources, and allows to obtain a Replay-Nonce. The acme_directory URL needs to support unauthenticated GET requests; ACME endpoints requiring authentication are not supported. https://tools.ietf.org/html/rfc8555#section-7.1.1 ''' def __init__(self, module, account): self.module = module self.directory_root = module.params['acme_directory'] self.version = module.params['acme_version'] self.directory, dummy = account.get_request(self.directory_root, get_only=True) # Check whether self.version matches what we expect if self.version == 1: for key in ('new-reg', 'new-authz', 'new-cert'): if key not in self.directory: raise ModuleFailException("ACME directory does not seem to follow protocol ACME v1") if self.version == 2: for key in ('newNonce', 'newAccount', 'newOrder'): if key not in self.directory: raise ModuleFailException("ACME directory does not seem to follow protocol ACME v2") def __getitem__(self, key): return self.directory[key] def get_nonce(self, resource=None): url = self.directory_root if self.version == 1 else self.directory['newNonce'] if resource is not None: url = resource dummy, info = fetch_url(self.module, url, method='HEAD') if info['status'] not in (200, 204): raise ModuleFailException("Failed to get replay-nonce, got status {0}".format(info['status'])) return info['replay-nonce'] class ACMEAccount(object): ''' ACME account object. Handles the authorized communication with the ACME server. Provides access to account bound information like the currently active authorizations and valid certificates ''' def __init__(self, module): # Set to true to enable logging of all signed requests self._debug = False self.module = module self.version = module.params['acme_version'] # account_key path and content are mutually exclusive self.key = module.params['account_key_src'] self.key_content = module.params['account_key_content'] # Grab account URI from module parameters. # Make sure empty string is treated as None. self.uri = module.params.get('account_uri') or None self._openssl_bin = module.get_bin_path('openssl', True) if self.key is not None or self.key_content is not None: error, self.key_data = self.parse_key(self.key, self.key_content) if error: raise ModuleFailException("error while parsing account key: %s" % error) self.jwk = self.key_data['jwk'] self.jws_header = { "alg": self.key_data['alg'], "jwk": self.jwk, } if self.uri: # Make sure self.jws_header is updated self.set_account_uri(self.uri) self.directory = ACMEDirectory(module, self) def get_keyauthorization(self, token): ''' Returns the key authorization for the given token https://tools.ietf.org/html/rfc8555#section-8.1 ''' accountkey_json = json.dumps(self.jwk, sort_keys=True, separators=(',', ':')) thumbprint = nopad_b64(hashlib.sha256(accountkey_json.encode('utf8')).digest()) return "{0}.{1}".format(token, thumbprint) def parse_key(self, key_file=None, key_content=None): ''' Parses an RSA or Elliptic Curve key file in PEM format and returns a pair (error, key_data). ''' if key_file is None and key_content is None: raise AssertionError('One of key_file and key_content must be specified!') if HAS_CURRENT_CRYPTOGRAPHY: return _parse_key_cryptography(self.module, key_file, key_content) else: return _parse_key_openssl(self._openssl_bin, self.module, key_file, key_content) def sign_request(self, protected, payload, key_data, encode_payload=True): try: if payload is None: # POST-as-GET payload64 = '' else: # POST if encode_payload: payload = self.module.jsonify(payload).encode('utf8') payload64 = nopad_b64(to_bytes(payload)) protected64 = nopad_b64(self.module.jsonify(protected).encode('utf8')) except Exception as e: raise ModuleFailException("Failed to encode payload / headers as JSON: {0}".format(e)) if HAS_CURRENT_CRYPTOGRAPHY: return _sign_request_cryptography(self.module, payload64, protected64, key_data) else: return _sign_request_openssl(self._openssl_bin, self.module, payload64, protected64, key_data) def _log(self, msg, data=None): ''' Write arguments to acme.log when logging is enabled. ''' if self._debug: with open('acme.log', 'ab') as f: f.write('[{0}] {1}\n'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%s'), msg).encode('utf-8')) if data is not None: f.write('{0}\n\n'.format(json.dumps(data, indent=2, sort_keys=True)).encode('utf-8')) def send_signed_request(self, url, payload, key_data=None, jws_header=None, parse_json_result=True, encode_payload=True): ''' Sends a JWS signed HTTP POST request to the ACME server and returns the response as dictionary https://tools.ietf.org/html/rfc8555#section-6.2 If payload is None, a POST-as-GET is performed. (https://tools.ietf.org/html/rfc8555#section-6.3) ''' key_data = key_data or self.key_data jws_header = jws_header or self.jws_header failed_tries = 0 while True: protected = copy.deepcopy(jws_header) protected["nonce"] = self.directory.get_nonce() if self.version != 1: protected["url"] = url self._log('URL', url) self._log('protected', protected) self._log('payload', payload) data = self.sign_request(protected, payload, key_data, encode_payload=encode_payload) if self.version == 1: data["header"] = jws_header.copy() for k, v in protected.items(): hv = data["header"].pop(k, None) self._log('signed request', data) data = self.module.jsonify(data) headers = { 'Content-Type': 'application/jose+json', } resp, info = fetch_url(self.module, url, data=data, headers=headers, method='POST') result = {} try: content = resp.read() except AttributeError: content = info.pop('body', None) if content or not parse_json_result: if (parse_json_result and info['content-type'].startswith('application/json')) or 400 <= info['status'] < 600: try: decoded_result = self.module.from_json(content.decode('utf8')) self._log('parsed result', decoded_result) # In case of badNonce error, try again (up to 5 times) # (https://tools.ietf.org/html/rfc8555#section-6.7) if (400 <= info['status'] < 600 and decoded_result.get('type') == 'urn:ietf:params:acme:error:badNonce' and failed_tries <= 5): failed_tries += 1 continue if parse_json_result: result = decoded_result else: result = content except ValueError: raise ModuleFailException("Failed to parse the ACME response: {0} {1}".format(url, content)) else: result = content return result, info def get_request(self, uri, parse_json_result=True, headers=None, get_only=False, fail_on_error=True): ''' Perform a GET-like request. Will try POST-as-GET for ACMEv2, with fallback to GET if server replies with a status code of 405. ''' if not get_only and self.version != 1: # Try POST-as-GET content, info = self.send_signed_request(uri, None, parse_json_result=False) if info['status'] == 405: # Instead, do unauthenticated GET get_only = True else: # Do unauthenticated GET get_only = True if get_only: # Perform unauthenticated GET resp, info = fetch_url(self.module, uri, method='GET', headers=headers) try: content = resp.read() except AttributeError: content = info.pop('body', None) # Process result if parse_json_result: result = {} if content: if info['content-type'].startswith('application/json'): try: result = self.module.from_json(content.decode('utf8')) except ValueError: raise ModuleFailException("Failed to parse the ACME response: {0} {1}".format(uri, content)) else: result = content else: result = content if fail_on_error and info['status'] >= 400: raise ModuleFailException("ACME request failed: CODE: {0} RESULT: {1}".format(info['status'], result)) return result, info def set_account_uri(self, uri): ''' Set account URI. For ACME v2, it needs to be used to sending signed requests. ''' self.uri = uri if self.version != 1: self.jws_header.pop('jwk') self.jws_header['kid'] = self.uri def _new_reg(self, contact=None, agreement=None, terms_agreed=False, allow_creation=True): ''' Registers a new ACME account. Returns a pair ``(created, data)``. Here, ``created`` is ``True`` if the account was created and ``False`` if it already existed (e.g. it was not newly created), or does not exist. In case the account was created or exists, ``data`` contains the account data; otherwise, it is ``None``. https://tools.ietf.org/html/rfc8555#section-7.3 ''' contact = contact or [] if self.version == 1: new_reg = { 'resource': 'new-reg', 'contact': contact } if agreement: new_reg['agreement'] = agreement else: new_reg['agreement'] = self.directory['meta']['terms-of-service'] url = self.directory['new-reg'] else: new_reg = { 'contact': contact } if not allow_creation: # https://tools.ietf.org/html/rfc8555#section-7.3.1 new_reg['onlyReturnExisting'] = True if terms_agreed: new_reg['termsOfServiceAgreed'] = True url = self.directory['newAccount'] result, info = self.send_signed_request(url, new_reg) if info['status'] in ([200, 201] if self.version == 1 else [201]): # Account did not exist if 'location' in info: self.set_account_uri(info['location']) return True, result elif info['status'] == (409 if self.version == 1 else 200): # Account did exist if result.get('status') == 'deactivated': # A bug in Pebble (https://github.com/letsencrypt/pebble/issues/179) and # Boulder (https://github.com/letsencrypt/boulder/issues/3971): this should # not return a valid account object according to # https://tools.ietf.org/html/rfc8555#section-7.3.6: # "Once an account is deactivated, the server MUST NOT accept further # requests authorized by that account's key." if not allow_creation: return False, None else: raise ModuleFailException("Account is deactivated") if 'location' in info: self.set_account_uri(info['location']) return False, result elif info['status'] == 400 and result['type'] == 'urn:ietf:params:acme:error:accountDoesNotExist' and not allow_creation: # Account does not exist (and we didn't try to create it) return False, None elif info['status'] == 403 and result['type'] == 'urn:ietf:params:acme:error:unauthorized' and 'deactivated' in (result.get('detail') or ''): # Account has been deactivated; currently works for Pebble; hasn't been # implemented for Boulder (https://github.com/letsencrypt/boulder/issues/3971), # might need adjustment in error detection. if not allow_creation: return False, None else: raise ModuleFailException("Account is deactivated") else: raise ModuleFailException("Error registering: {0} {1}".format(info['status'], result)) def get_account_data(self): ''' Retrieve account information. Can only be called when the account URI is already known (such as after calling setup_account). Return None if the account was deactivated, or a dict otherwise. ''' if self.uri is None: raise ModuleFailException("Account URI unknown") if self.version == 1: data = {} data['resource'] = 'reg' result, info = self.send_signed_request(self.uri, data) else: # try POST-as-GET first (draft-15 or newer) data = None result, info = self.send_signed_request(self.uri, data) # check whether that failed with a malformed request error if info['status'] >= 400 and result.get('type') == 'urn:ietf:params:acme:error:malformed': # retry as a regular POST (with no changed data) for pre-draft-15 ACME servers data = {} result, info = self.send_signed_request(self.uri, data) if info['status'] in (400, 403) and result.get('type') == 'urn:ietf:params:acme:error:unauthorized': # Returned when account is deactivated return None if info['status'] in (400, 404) and result.get('type') == 'urn:ietf:params:acme:error:accountDoesNotExist': # Returned when account does not exist return None if info['status'] < 200 or info['status'] >= 300: raise ModuleFailException("Error getting account data from {2}: {0} {1}".format(info['status'], result, self.uri)) return result def setup_account(self, contact=None, agreement=None, terms_agreed=False, allow_creation=True, remove_account_uri_if_not_exists=False): ''' Detect or create an account on the ACME server. For ACME v1, as the only way (without knowing an account URI) to test if an account exists is to try and create one with the provided account key, this method will always result in an account being present (except on error situations). For ACME v2, a new account will only be created if ``allow_creation`` is set to True. For ACME v2, ``check_mode`` is fully respected. For ACME v1, the account might be created if it does not yet exist. Return a pair ``(created, account_data)``. Here, ``created`` will be ``True`` in case the account was created or would be created (check mode). ``account_data`` will be the current account data, or ``None`` if the account does not exist. The account URI will be stored in ``self.uri``; if it is ``None``, the account does not exist. https://tools.ietf.org/html/rfc8555#section-7.3 ''' if self.uri is not None: created = False # Verify that the account key belongs to the URI. # (If update_contact is True, this will be done below.) account_data = self.get_account_data() if account_data is None: if remove_account_uri_if_not_exists and not allow_creation: self.uri = None else: raise ModuleFailException("Account is deactivated or does not exist!") else: created, account_data = self._new_reg( contact, agreement=agreement, terms_agreed=terms_agreed, allow_creation=allow_creation and not self.module.check_mode ) if self.module.check_mode and self.uri is None and allow_creation: created = True account_data = { 'contact': contact or [] } return created, account_data def update_account(self, account_data, contact=None): ''' Update an account on the ACME server. Check mode is fully respected. The current account data must be provided as ``account_data``. Return a pair ``(updated, account_data)``, where ``updated`` is ``True`` in case something changed (contact info updated) or would be changed (check mode), and ``account_data`` the updated account data. https://tools.ietf.org/html/rfc8555#section-7.3.2 ''' # Create request update_request = {} if contact is not None and account_data.get('contact', []) != contact: update_request['contact'] = list(contact) # No change? if not update_request: return False, dict(account_data) # Apply change if self.module.check_mode: account_data = dict(account_data) account_data.update(update_request) else: if self.version == 1: update_request['resource'] = 'reg' account_data, dummy = self.send_signed_request(self.uri, update_request) return True, account_data def _normalize_ip(ip): try: return to_native(compat_ipaddress.ip_address(to_text(ip)).compressed) except ValueError: # We don't want to error out on something IPAddress() can't parse return ip def openssl_get_csr_identifiers(openssl_binary, module, csr_filename): ''' Return a set of requested identifiers (CN and SANs) for the CSR. Each identifier is a pair (type, identifier), where type is either 'dns' or 'ip'. ''' openssl_csr_cmd = [openssl_binary, "req", "-in", csr_filename, "-noout", "-text"] dummy, out, dummy = module.run_command(openssl_csr_cmd, check_rc=True) identifiers = set([]) common_name = re.search(r"Subject:.* CN\s?=\s?([^\s,;/]+)", to_text(out, errors='surrogate_or_strict')) if common_name is not None: identifiers.add(('dns', common_name.group(1))) subject_alt_names = re.search( r"X509v3 Subject Alternative Name: (?:critical)?\n +([^\n]+)\n", to_text(out, errors='surrogate_or_strict'), re.MULTILINE | re.DOTALL) if subject_alt_names is not None: for san in subject_alt_names.group(1).split(", "): if san.lower().startswith("dns:"): identifiers.add(('dns', san[4:])) elif san.lower().startswith("ip:"): identifiers.add(('ip', _normalize_ip(san[3:]))) elif san.lower().startswith("ip address:"): identifiers.add(('ip', _normalize_ip(san[11:]))) else: raise ModuleFailException('Found unsupported SAN identifier "{0}"'.format(san)) return identifiers def cryptography_get_csr_identifiers(module, csr_filename): ''' Return a set of requested identifiers (CN and SANs) for the CSR. Each identifier is a pair (type, identifier), where type is either 'dns' or 'ip'. ''' identifiers = set([]) csr = cryptography.x509.load_pem_x509_csr(read_file(csr_filename), _cryptography_backend) for sub in csr.subject: if sub.oid == cryptography.x509.oid.NameOID.COMMON_NAME: identifiers.add(('dns', sub.value)) for extension in csr.extensions: if extension.oid == cryptography.x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME: for name in extension.value: if isinstance(name, cryptography.x509.DNSName): identifiers.add(('dns', name.value)) elif isinstance(name, cryptography.x509.IPAddress): identifiers.add(('ip', name.value.compressed)) else: raise ModuleFailException('Found unsupported SAN identifier {0}'.format(name)) return identifiers def cryptography_get_cert_days(module, cert_file, now=None): ''' Return the days the certificate in cert_file remains valid and -1 if the file was not found. If cert_file contains more than one certificate, only the first one will be considered. ''' if not os.path.exists(cert_file): return -1 try: cert = cryptography.x509.load_pem_x509_certificate(read_file(cert_file), _cryptography_backend) except Exception as e: raise ModuleFailException('Cannot parse certificate {0}: {1}'.format(cert_file, e)) if now is None: now = datetime.datetime.now() return (cert.not_valid_after - now).days def set_crypto_backend(module): ''' Sets which crypto backend to use (default: auto detection). Does not care whether a new enough cryptoraphy is available or not. Must be called before any real stuff is done which might evaluate ``HAS_CURRENT_CRYPTOGRAPHY``. ''' global HAS_CURRENT_CRYPTOGRAPHY # Choose backend backend = module.params['select_crypto_backend'] if backend == 'auto': pass elif backend == 'openssl': HAS_CURRENT_CRYPTOGRAPHY = False elif backend == 'cryptography': try: cryptography.__version__ except Exception as dummy: module.fail_json(msg=missing_required_lib('cryptography')) HAS_CURRENT_CRYPTOGRAPHY = True else: module.fail_json(msg='Unknown crypto backend "{0}"!'.format(backend)) # Inform about choices if HAS_CURRENT_CRYPTOGRAPHY: module.debug('Using cryptography backend (library version {0})'.format(CRYPTOGRAPHY_VERSION)) return 'cryptography' else: module.debug('Using OpenSSL binary backend') return 'openssl' def process_links(info, callback): ''' Process link header, calls callback for every link header with the URL and relation as options. ''' if 'link' in info: link = info['link'] for url, relation in re.findall(r'<([^>]+)>;\s*rel="(\w+)"', link): callback(unquote(url), relation) def get_default_argspec(): ''' Provides default argument spec for the options documented in the acme doc fragment. ''' return dict( account_key_src=dict(type='path', aliases=['account_key']), account_key_content=dict(type='str', no_log=True), account_uri=dict(type='str'), acme_directory=dict(type='str'), acme_version=dict(type='int', choices=[1, 2]), validate_certs=dict(type='bool', default=True), select_crypto_backend=dict(type='str', default='auto', choices=['auto', 'openssl', 'cryptography']), ) def handle_standard_module_arguments(module, needs_acme_v2=False): ''' Do standard module setup, argument handling and warning emitting. ''' backend = set_crypto_backend(module) if not module.params['validate_certs']: module.warn( 'Disabling certificate validation for communications with ACME endpoint. ' 'This should only be done for testing against a local ACME server for ' 'development purposes, but *never* for production purposes.' ) if module.params['acme_version'] is None: module.params['acme_version'] = 1 module.deprecate("The option 'acme_version' will be required from Ansible 2.14 on", version='2.14') if module.params['acme_directory'] is None: module.params['acme_directory'] = 'https://acme-staging.api.letsencrypt.org/directory' module.deprecate("The option 'acme_directory' will be required from Ansible 2.14 on", version='2.14') if needs_acme_v2 and module.params['acme_version'] < 2: module.fail_json(msg='The {0} module requires the ACME v2 protocol!'.format(module._name)) # AnsibleModule() changes the locale, so change it back to C because we rely on time.strptime() when parsing certificate dates. module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C') locale.setlocale(locale.LC_ALL, 'C') return backend
closed
ansible/ansible
https://github.com/ansible/ansible
58,284
recursive copy with remote_src=yes does not recurse beyond first level
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Recursively copying changed directories does not work if the changes are deeper than one directory level. If contents the top-level src directory appears unchanged, the whole directory appears unchanged. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> copy ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.1 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/akorsunsky/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.7/site-packages/ansible executable location = /usr/bin/ansible python version = 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True INTERPRETER_PYTHON(/etc/ansible/ansible.cfg) = auto ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> - Distribution: Fedora 30, 64 Bit - Python: 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] - `uname -a`: Linux localhost 5.1.9-300.fc30.x86_64 #1 SMP Tue Jun 11 16:17:54 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux ##### STEPS TO REPRODUCE <!--- Paste example playbooks or commands between quotes below --> ```bash mkdir -p /tmp/src/a/b/ /tmp/dest/a/b/ touch /tmp/src/a/b/newfile ansible localhost -m copy -a "src=/tmp/src/ dest=/tmp/dest/ remote_src=yes" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> `/tmp/src/a/b/newfile` copied to `/tmp/dest/a/b/newfile`, task marked as changed. ##### ACTUAL RESULTS `/tmp/dest/a/b/newfile` does not exist. Task marked as not changed. <!--- Paste verbatim command output between quotes --> ```paste below localhost | SUCCESS => { "changed": false, "checksum": null, "dest": "/tmp/dest/", "gid": 1269600003, "group": "akorsunsky", "md5sum": null, "mode": "0775", "owner": "akorsunsky", "size": 60, "src": "/tmp/src/", "state": "directory", "uid": 1269600003 } ```
https://github.com/ansible/ansible/issues/58284
https://github.com/ansible/ansible/pull/58323
26236f474ba8aa600d321c9cb7c5b11d123928ac
b7e38dfa52024c1363cdd37fac3fce52ad421f08
2019-06-24T15:11:09Z
python
2019-10-30T16:17:11Z
changelogs/fragments/58323-copy-deep-recursive-with-remote_src.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
58,284
recursive copy with remote_src=yes does not recurse beyond first level
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Recursively copying changed directories does not work if the changes are deeper than one directory level. If contents the top-level src directory appears unchanged, the whole directory appears unchanged. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> copy ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.1 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/akorsunsky/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.7/site-packages/ansible executable location = /usr/bin/ansible python version = 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True INTERPRETER_PYTHON(/etc/ansible/ansible.cfg) = auto ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> - Distribution: Fedora 30, 64 Bit - Python: 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] - `uname -a`: Linux localhost 5.1.9-300.fc30.x86_64 #1 SMP Tue Jun 11 16:17:54 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux ##### STEPS TO REPRODUCE <!--- Paste example playbooks or commands between quotes below --> ```bash mkdir -p /tmp/src/a/b/ /tmp/dest/a/b/ touch /tmp/src/a/b/newfile ansible localhost -m copy -a "src=/tmp/src/ dest=/tmp/dest/ remote_src=yes" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> `/tmp/src/a/b/newfile` copied to `/tmp/dest/a/b/newfile`, task marked as changed. ##### ACTUAL RESULTS `/tmp/dest/a/b/newfile` does not exist. Task marked as not changed. <!--- Paste verbatim command output between quotes --> ```paste below localhost | SUCCESS => { "changed": false, "checksum": null, "dest": "/tmp/dest/", "gid": 1269600003, "group": "akorsunsky", "md5sum": null, "mode": "0775", "owner": "akorsunsky", "size": 60, "src": "/tmp/src/", "state": "directory", "uid": 1269600003 } ```
https://github.com/ansible/ansible/issues/58284
https://github.com/ansible/ansible/pull/58323
26236f474ba8aa600d321c9cb7c5b11d123928ac
b7e38dfa52024c1363cdd37fac3fce52ad421f08
2019-06-24T15:11:09Z
python
2019-10-30T16:17:11Z
lib/ansible/modules/files/copy.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Michael DeHaan <[email protected]> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: copy version_added: historical short_description: Copy files to remote locations description: - The C(copy) module copies a file from the local or remote machine to a location on the remote machine. - Use the M(fetch) module to copy files from remote locations to the local box. - If you need variable interpolation in copied files, use the M(template) module. Using a variable in the C(content) field will result in unpredictable output. - For Windows targets, use the M(win_copy) module instead. options: src: description: - Local path to a file to copy to the remote server. - This can be absolute or relative. - If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", the directory itself with all contents is copied. This behavior is similar to the C(rsync) command line tool. type: path content: description: - When used instead of C(src), sets the contents of a file directly to the specified value. - Works only when C(dest) is a file. Creates the file if it does not exist. - For advanced formatting or if C(content) contains a variable, use the M(template) module. type: str version_added: '1.1' dest: description: - Remote absolute path where the file should be copied to. - If C(src) is a directory, this must be a directory too. - If C(dest) is a non-existent path and if either C(dest) ends with "/" or C(src) is a directory, C(dest) is created. - If I(dest) is a relative path, the starting directory is determined by the remote host. - If C(src) and C(dest) are files, the parent directory of C(dest) is not created and the task fails if it does not already exist. type: path required: yes backup: description: - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. type: bool default: no version_added: '0.7' force: description: - Influence whether the remote file must always be replaced. - If C(yes), the remote file will be replaced when contents are different than the source. - If C(no), the file will only be transferred if the destination does not exist. - Alias C(thirsty) has been deprecated and will be removed in 2.13. type: bool default: yes aliases: [ thirsty ] version_added: '1.1' mode: description: - The permissions of the destination file or directory. - For those used to C(/usr/bin/chmod) remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like C(0644) or C(01777))or quote it (like C('644') or C('1777')) so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results. - As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, C(u+rwx) or C(u=rw,g=r,o=r)). - As of Ansible 2.3, the mode may also be the special string C(preserve). - C(preserve) means that the file will be given the same permissions as the source file. type: path directory_mode: description: - When doing a recursive copy set the mode for the directories. - If this is not set we will use the system defaults. - The mode is only set on directories which are newly created, and will not affect those that already existed. type: raw version_added: '1.5' remote_src: description: - Influence whether C(src) needs to be transferred or already is present remotely. - If C(no), it will search for C(src) at originating/master machine. - If C(yes) it will go to the remote/target machine for the C(src). - C(remote_src) supports recursive copying as of version 2.8. - C(remote_src) only works with C(mode=preserve) as of version 2.6. type: bool default: no version_added: '2.0' follow: description: - This flag indicates that filesystem links in the destination, if they exist, should be followed. type: bool default: no version_added: '1.8' local_follow: description: - This flag indicates that filesystem links in the source tree, if they exist, should be followed. type: bool default: yes version_added: '2.4' checksum: description: - SHA1 checksum of the file being transferred. - Used to validate that the copy of the file was successful. - If this is not provided, ansible will use the local calculated checksum of the src file. type: str version_added: '2.5' extends_documentation_fragment: - decrypt - files - validate notes: - The M(copy) module recursively copy facility does not scale to lots (>hundreds) of files. seealso: - module: assemble - module: fetch - module: file - module: synchronize - module: template - module: win_copy author: - Ansible Core Team - Michael DeHaan ''' EXAMPLES = r''' - name: Copy file with owner and permissions copy: src: /srv/myfiles/foo.conf dest: /etc/foo.conf owner: foo group: foo mode: '0644' - name: Copy file with owner and permission, using symbolic representation copy: src: /srv/myfiles/foo.conf dest: /etc/foo.conf owner: foo group: foo mode: u=rw,g=r,o=r - name: Another symbolic mode example, adding some permissions and removing others copy: src: /srv/myfiles/foo.conf dest: /etc/foo.conf owner: foo group: foo mode: u+rw,g-wx,o-rwx - name: Copy a new "ntp.conf file into place, backing up the original if it differs from the copied version copy: src: /mine/ntp.conf dest: /etc/ntp.conf owner: root group: root mode: '0644' backup: yes - name: Copy a new "sudoers" file into place, after passing validation with visudo copy: src: /mine/sudoers dest: /etc/sudoers validate: /usr/sbin/visudo -csf %s - name: Copy a "sudoers" file on the remote machine for editing copy: src: /etc/sudoers dest: /etc/sudoers.edit remote_src: yes validate: /usr/sbin/visudo -csf %s - name: Copy using inline content copy: content: '# This file was moved to /etc/other.conf' dest: /etc/mine.conf - name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf copy: src: /etc/foo.conf dest: /path/to/link # link to /path/to/file follow: yes - name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf copy: src: /etc/foo.conf dest: /path/to/link # link to /path/to/file follow: no ''' RETURN = r''' dest: description: Destination file/path returned: success type: str sample: /path/to/file.txt src: description: Source file used for the copy on the target machine returned: changed type: str sample: /home/httpd/.ansible/tmp/ansible-tmp-1423796390.97-147729857856000/source md5sum: description: MD5 checksum of the file after running copy returned: when supported type: str sample: 2a5aeecc61dc98c4d780b14b330e3282 checksum: description: SHA1 checksum of the file after running copy returned: success type: str sample: 6e642bb8dd5c2e027bf21dd923337cbb4214f827 backup_file: description: Name of backup file created returned: changed and if backup=yes type: str sample: /path/to/file.txt.2015-02-12@22:09~ gid: description: Group id of the file, after execution returned: success type: int sample: 100 group: description: Group of the file, after execution returned: success type: str sample: httpd owner: description: Owner of the file, after execution returned: success type: str sample: httpd uid: description: Owner id of the file, after execution returned: success type: int sample: 100 mode: description: Permissions of the target, after execution returned: success type: str sample: 0644 size: description: Size of the target, after execution returned: success type: int sample: 1220 state: description: State of the target, after execution returned: success type: str sample: file ''' import errno import filecmp import grp import os import os.path import platform import pwd import shutil import stat import tempfile import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.process import get_bin_path from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils.six import PY3 # The AnsibleModule object module = None class AnsibleModuleError(Exception): def __init__(self, results): self.results = results # Once we get run_command moved into common, we can move this into a common/files module. We can't # until then because of the module.run_command() method. We may need to move it into # basic::AnsibleModule() until then but if so, make it a private function so that we don't have to # keep it for backwards compatibility later. def clear_facls(path): setfacl = get_bin_path('setfacl', True) # FIXME "setfacl -b" is available on Linux and FreeBSD. There is "setfacl -D e" on z/OS. Others? acl_command = [setfacl, '-b', path] b_acl_command = [to_bytes(x) for x in acl_command] rc, out, err = module.run_command(b_acl_command, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')) if rc != 0: raise RuntimeError('Error running "{0}": stdout: "{1}"; stderr: "{2}"'.format(' '.join(b_acl_command), out, err)) def split_pre_existing_dir(dirname): ''' Return the first pre-existing directory and a list of the new directories that will be created. ''' head, tail = os.path.split(dirname) b_head = to_bytes(head, errors='surrogate_or_strict') if head == '': return ('.', [tail]) if not os.path.exists(b_head): if head == '/': raise AnsibleModuleError(results={'msg': "The '/' directory doesn't exist on this machine."}) (pre_existing_dir, new_directory_list) = split_pre_existing_dir(head) else: return (head, [tail]) new_directory_list.append(tail) return (pre_existing_dir, new_directory_list) def adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed): ''' Walk the new directories list and make sure that permissions are as we would expect ''' if new_directory_list: working_dir = os.path.join(pre_existing_dir, new_directory_list.pop(0)) directory_args['path'] = working_dir changed = module.set_fs_attributes_if_different(directory_args, changed) changed = adjust_recursive_directory_permissions(working_dir, new_directory_list, module, directory_args, changed) return changed def chown_recursive(path, module): changed = False owner = module.params['owner'] group = module.params['group'] if owner is not None: if not module.check_mode: for dirpath, dirnames, filenames in os.walk(path): owner_changed = module.set_owner_if_different(dirpath, owner, False) if owner_changed is True: changed = owner_changed for dir in [os.path.join(dirpath, d) for d in dirnames]: owner_changed = module.set_owner_if_different(dir, owner, False) if owner_changed is True: changed = owner_changed for file in [os.path.join(dirpath, f) for f in filenames]: owner_changed = module.set_owner_if_different(file, owner, False) if owner_changed is True: changed = owner_changed else: uid = pwd.getpwnam(owner).pw_uid for dirpath, dirnames, filenames in os.walk(path): owner_changed = (os.stat(dirpath).st_uid != uid) if owner_changed is True: changed = owner_changed for dir in [os.path.join(dirpath, d) for d in dirnames]: owner_changed = (os.stat(dir).st_uid != uid) if owner_changed is True: changed = owner_changed for file in [os.path.join(dirpath, f) for f in filenames]: owner_changed = (os.stat(file).st_uid != uid) if owner_changed is True: changed = owner_changed if group is not None: if not module.check_mode: for dirpath, dirnames, filenames in os.walk(path): group_changed = module.set_group_if_different(dirpath, group, False) if group_changed is True: changed = group_changed for dir in [os.path.join(dirpath, d) for d in dirnames]: group_changed = module.set_group_if_different(dir, group, False) if group_changed is True: changed = group_changed for file in [os.path.join(dirpath, f) for f in filenames]: group_changed = module.set_group_if_different(file, group, False) if group_changed is True: changed = group_changed else: gid = grp.getgrnam(group).gr_gid for dirpath, dirnames, filenames in os.walk(path): group_changed = (os.stat(dirpath).st_gid != gid) if group_changed is True: changed = group_changed for dir in [os.path.join(dirpath, d) for d in dirnames]: group_changed = (os.stat(dir).st_gid != gid) if group_changed is True: changed = group_changed for file in [os.path.join(dirpath, f) for f in filenames]: group_changed = (os.stat(file).st_gid != gid) if group_changed is True: changed = group_changed return changed def copy_diff_files(src, dest, module): changed = False owner = module.params['owner'] group = module.params['group'] local_follow = module.params['local_follow'] diff_files = filecmp.dircmp(src, dest).diff_files if len(diff_files): changed = True if not module.check_mode: for item in diff_files: src_item_path = os.path.join(src, item) dest_item_path = os.path.join(dest, item) b_src_item_path = to_bytes(src_item_path, errors='surrogate_or_strict') b_dest_item_path = to_bytes(dest_item_path, errors='surrogate_or_strict') if os.path.islink(b_src_item_path) and local_follow is False: linkto = os.readlink(b_src_item_path) os.symlink(linkto, b_dest_item_path) else: shutil.copyfile(b_src_item_path, b_dest_item_path) if owner is not None: module.set_owner_if_different(b_dest_item_path, owner, False) if group is not None: module.set_group_if_different(b_dest_item_path, group, False) changed = True return changed def copy_left_only(src, dest, module): changed = False owner = module.params['owner'] group = module.params['group'] local_follow = module.params['local_follow'] left_only = filecmp.dircmp(src, dest).left_only if len(left_only): changed = True if not module.check_mode: for item in left_only: src_item_path = os.path.join(src, item) dest_item_path = os.path.join(dest, item) b_src_item_path = to_bytes(src_item_path, errors='surrogate_or_strict') b_dest_item_path = to_bytes(dest_item_path, errors='surrogate_or_strict') if os.path.islink(b_src_item_path) and os.path.isdir(b_src_item_path) and local_follow is True: shutil.copytree(b_src_item_path, b_dest_item_path, symlinks=not(local_follow)) chown_recursive(b_dest_item_path, module) if os.path.islink(b_src_item_path) and os.path.isdir(b_src_item_path) and local_follow is False: linkto = os.readlink(b_src_item_path) os.symlink(linkto, b_dest_item_path) if os.path.islink(b_src_item_path) and os.path.isfile(b_src_item_path) and local_follow is True: shutil.copyfile(b_src_item_path, b_dest_item_path) if owner is not None: module.set_owner_if_different(b_dest_item_path, owner, False) if group is not None: module.set_group_if_different(b_dest_item_path, group, False) if os.path.islink(b_src_item_path) and os.path.isfile(b_src_item_path) and local_follow is False: linkto = os.readlink(b_src_item_path) os.symlink(linkto, b_dest_item_path) if not os.path.islink(b_src_item_path) and os.path.isfile(b_src_item_path): shutil.copyfile(b_src_item_path, b_dest_item_path) if owner is not None: module.set_owner_if_different(b_dest_item_path, owner, False) if group is not None: module.set_group_if_different(b_dest_item_path, group, False) if not os.path.islink(b_src_item_path) and os.path.isdir(b_src_item_path): shutil.copytree(b_src_item_path, b_dest_item_path, symlinks=not(local_follow)) chown_recursive(b_dest_item_path, module) changed = True return changed def copy_common_dirs(src, dest, module): changed = False common_dirs = filecmp.dircmp(src, dest).common_dirs for item in common_dirs: src_item_path = os.path.join(src, item) dest_item_path = os.path.join(dest, item) b_src_item_path = to_bytes(src_item_path, errors='surrogate_or_strict') b_dest_item_path = to_bytes(dest_item_path, errors='surrogate_or_strict') diff_files_changed = copy_diff_files(b_src_item_path, b_dest_item_path, module) left_only_changed = copy_left_only(b_src_item_path, b_dest_item_path, module) if diff_files_changed or left_only_changed: changed = True return changed def main(): global module module = AnsibleModule( # not checking because of daisy chain to file module argument_spec=dict( src=dict(type='path'), _original_basename=dict(type='str'), # used to handle 'dest is a directory' via template, a slight hack content=dict(type='str', no_log=True), dest=dict(type='path', required=True), backup=dict(type='bool', default=False), force=dict(type='bool', default=True, aliases=['thirsty']), validate=dict(type='str'), directory_mode=dict(type='raw'), remote_src=dict(type='bool'), local_follow=dict(type='bool'), checksum=dict(type='str'), ), add_file_common_args=True, supports_check_mode=True, ) if module.params.get('thirsty'): module.deprecate('The alias "thirsty" has been deprecated and will be removed, use "force" instead', version='2.13') src = module.params['src'] b_src = to_bytes(src, errors='surrogate_or_strict') dest = module.params['dest'] # Make sure we always have a directory component for later processing if os.path.sep not in dest: dest = '.{0}{1}'.format(os.path.sep, dest) b_dest = to_bytes(dest, errors='surrogate_or_strict') backup = module.params['backup'] force = module.params['force'] _original_basename = module.params.get('_original_basename', None) validate = module.params.get('validate', None) follow = module.params['follow'] local_follow = module.params['local_follow'] mode = module.params['mode'] owner = module.params['owner'] group = module.params['group'] remote_src = module.params['remote_src'] checksum = module.params['checksum'] if not os.path.exists(b_src): module.fail_json(msg="Source %s not found" % (src)) if not os.access(b_src, os.R_OK): module.fail_json(msg="Source %s not readable" % (src)) # Preserve is usually handled in the action plugin but mode + remote_src has to be done on the # remote host if module.params['mode'] == 'preserve': module.params['mode'] = '0%03o' % stat.S_IMODE(os.stat(b_src).st_mode) mode = module.params['mode'] checksum_dest = None if os.path.isfile(src): checksum_src = module.sha1(src) else: checksum_src = None # Backwards compat only. This will be None in FIPS mode try: if os.path.isfile(src): md5sum_src = module.md5(src) else: md5sum_src = None except ValueError: md5sum_src = None changed = False if checksum and checksum_src != checksum: module.fail_json( msg='Copied file does not match the expected checksum. Transfer failed.', checksum=checksum_src, expected_checksum=checksum ) # Special handling for recursive copy - create intermediate dirs if _original_basename and dest.endswith(os.sep): dest = os.path.join(dest, _original_basename) b_dest = to_bytes(dest, errors='surrogate_or_strict') dirname = os.path.dirname(dest) b_dirname = to_bytes(dirname, errors='surrogate_or_strict') if not os.path.exists(b_dirname): try: (pre_existing_dir, new_directory_list) = split_pre_existing_dir(dirname) except AnsibleModuleError as e: e.result['msg'] += ' Could not copy to {0}'.format(dest) module.fail_json(**e.results) os.makedirs(b_dirname) directory_args = module.load_file_common_arguments(module.params) directory_mode = module.params["directory_mode"] if directory_mode is not None: directory_args['mode'] = directory_mode else: directory_args['mode'] = None adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed) if os.path.isdir(b_dest): basename = os.path.basename(src) if _original_basename: basename = _original_basename dest = os.path.join(dest, basename) b_dest = to_bytes(dest, errors='surrogate_or_strict') if os.path.exists(b_dest): if os.path.islink(b_dest) and follow: b_dest = os.path.realpath(b_dest) dest = to_native(b_dest, errors='surrogate_or_strict') if not force: module.exit_json(msg="file already exists", src=src, dest=dest, changed=False) if os.access(b_dest, os.R_OK) and os.path.isfile(b_dest): checksum_dest = module.sha1(dest) else: if not os.path.exists(os.path.dirname(b_dest)): try: # os.path.exists() can return false in some # circumstances where the directory does not have # the execute bit for the current user set, in # which case the stat() call will raise an OSError os.stat(os.path.dirname(b_dest)) except OSError as e: if "permission denied" in to_native(e).lower(): module.fail_json(msg="Destination directory %s is not accessible" % (os.path.dirname(dest))) module.fail_json(msg="Destination directory %s does not exist" % (os.path.dirname(dest))) if not os.access(os.path.dirname(b_dest), os.W_OK) and not module.params['unsafe_writes']: module.fail_json(msg="Destination %s not writable" % (os.path.dirname(dest))) backup_file = None if checksum_src != checksum_dest or os.path.islink(b_dest): if not module.check_mode: try: if backup: if os.path.exists(b_dest): backup_file = module.backup_local(dest) # allow for conversion from symlink. if os.path.islink(b_dest): os.unlink(b_dest) open(b_dest, 'w').close() if validate: # if we have a mode, make sure we set it on the temporary # file source as some validations may require it if mode is not None: module.set_mode_if_different(src, mode, False) if owner is not None: module.set_owner_if_different(src, owner, False) if group is not None: module.set_group_if_different(src, group, False) if "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % (validate)) (rc, out, err) = module.run_command(validate % src) if rc != 0: module.fail_json(msg="failed to validate", exit_status=rc, stdout=out, stderr=err) b_mysrc = b_src if remote_src and os.path.isfile(b_src): _, b_mysrc = tempfile.mkstemp(dir=os.path.dirname(b_dest)) shutil.copyfile(b_src, b_mysrc) try: shutil.copystat(b_src, b_mysrc) except OSError as err: if err.errno == errno.ENOSYS and mode == "preserve": module.warn("Unable to copy stats {0}".format(to_native(b_src))) else: raise # might be needed below if PY3 and hasattr(os, 'listxattr'): try: src_has_acls = 'system.posix_acl_access' in os.listxattr(src) except Exception as e: # assume unwanted ACLs by default src_has_acls = True module.atomic_move(b_mysrc, dest, unsafe_writes=module.params['unsafe_writes']) if PY3 and hasattr(os, 'listxattr') and platform.system() == 'Linux' and not remote_src: # atomic_move used above to copy src into dest might, in some cases, # use shutil.copy2 which in turn uses shutil.copystat. # Since Python 3.3, shutil.copystat copies file extended attributes: # https://docs.python.org/3/library/shutil.html#shutil.copystat # os.listxattr (along with others) was added to handle the operation. # This means that on Python 3 we are copying the extended attributes which includes # the ACLs on some systems - further limited to Linux as the documentation above claims # that the extended attributes are copied only on Linux. Also, os.listxattr is only # available on Linux. # If not remote_src, then the file was copied from the controller. In that # case, any filesystem ACLs are artifacts of the copy rather than preservation # of existing attributes. Get rid of them: if src_has_acls: # FIXME If dest has any default ACLs, there are not applied to src now because # they were overridden by copystat. Should/can we do anything about this? # 'system.posix_acl_default' in os.listxattr(os.path.dirname(b_dest)) try: clear_facls(dest) except ValueError as e: if 'setfacl' in to_native(e): # No setfacl so we're okay. The controller couldn't have set a facl # without the setfacl command pass else: raise except RuntimeError as e: # setfacl failed. if 'Operation not supported' in to_native(e): # The file system does not support ACLs. pass else: raise except (IOError, OSError): module.fail_json(msg="failed to copy: %s to %s" % (src, dest), traceback=traceback.format_exc()) changed = True else: changed = False if checksum_src is None and checksum_dest is None: if remote_src and os.path.isdir(module.params['src']): b_src = to_bytes(module.params['src'], errors='surrogate_or_strict') b_dest = to_bytes(module.params['dest'], errors='surrogate_or_strict') if src.endswith(os.path.sep) and os.path.isdir(module.params['dest']): diff_files_changed = copy_diff_files(b_src, b_dest, module) left_only_changed = copy_left_only(b_src, b_dest, module) common_dirs_changed = copy_common_dirs(b_src, b_dest, module) owner_group_changed = chown_recursive(b_dest, module) if diff_files_changed or left_only_changed or common_dirs_changed or owner_group_changed: changed = True if src.endswith(os.path.sep) and not os.path.exists(module.params['dest']): b_basename = to_bytes(os.path.basename(src), errors='surrogate_or_strict') b_dest = to_bytes(os.path.join(b_dest, b_basename), errors='surrogate_or_strict') b_src = to_bytes(os.path.join(module.params['src'], ""), errors='surrogate_or_strict') if not module.check_mode: shutil.copytree(b_src, b_dest, symlinks=not(local_follow)) chown_recursive(dest, module) changed = True if not src.endswith(os.path.sep) and os.path.isdir(module.params['dest']): b_basename = to_bytes(os.path.basename(src), errors='surrogate_or_strict') b_dest = to_bytes(os.path.join(b_dest, b_basename), errors='surrogate_or_strict') b_src = to_bytes(os.path.join(module.params['src'], ""), errors='surrogate_or_strict') if not module.check_mode and not os.path.exists(b_dest): shutil.copytree(b_src, b_dest, symlinks=not(local_follow)) changed = True chown_recursive(dest, module) if module.check_mode and not os.path.exists(b_dest): changed = True if os.path.exists(b_dest): diff_files_changed = copy_diff_files(b_src, b_dest, module) left_only_changed = copy_left_only(b_src, b_dest, module) common_dirs_changed = copy_common_dirs(b_src, b_dest, module) owner_group_changed = chown_recursive(b_dest, module) if diff_files_changed or left_only_changed or common_dirs_changed or owner_group_changed: changed = True if not src.endswith(os.path.sep) and not os.path.exists(module.params['dest']): b_basename = to_bytes(os.path.basename(module.params['src']), errors='surrogate_or_strict') b_dest = to_bytes(os.path.join(b_dest, b_basename), errors='surrogate_or_strict') if not module.check_mode and not os.path.exists(b_dest): os.makedirs(b_dest) b_src = to_bytes(os.path.join(module.params['src'], ""), errors='surrogate_or_strict') diff_files_changed = copy_diff_files(b_src, b_dest, module) left_only_changed = copy_left_only(b_src, b_dest, module) common_dirs_changed = copy_common_dirs(b_src, b_dest, module) owner_group_changed = chown_recursive(b_dest, module) if diff_files_changed or left_only_changed or common_dirs_changed or owner_group_changed: changed = True if module.check_mode and not os.path.exists(b_dest): changed = True res_args = dict( dest=dest, src=src, md5sum=md5sum_src, checksum=checksum_src, changed=changed ) if backup_file: res_args['backup_file'] = backup_file module.params['dest'] = dest if not module.check_mode: file_args = module.load_file_common_arguments(module.params) res_args['changed'] = module.set_fs_attributes_if_different(file_args, res_args['changed']) module.exit_json(**res_args) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
58,284
recursive copy with remote_src=yes does not recurse beyond first level
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY Recursively copying changed directories does not work if the changes are deeper than one directory level. If contents the top-level src directory appears unchanged, the whole directory appears unchanged. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> copy ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.1 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/akorsunsky/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.7/site-packages/ansible executable location = /usr/bin/ansible python version = 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True INTERPRETER_PYTHON(/etc/ansible/ansible.cfg) = auto ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> - Distribution: Fedora 30, 64 Bit - Python: 3.7.3 (default, May 11 2019, 00:38:04) [GCC 9.1.1 20190503 (Red Hat 9.1.1-1)] - `uname -a`: Linux localhost 5.1.9-300.fc30.x86_64 #1 SMP Tue Jun 11 16:17:54 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux ##### STEPS TO REPRODUCE <!--- Paste example playbooks or commands between quotes below --> ```bash mkdir -p /tmp/src/a/b/ /tmp/dest/a/b/ touch /tmp/src/a/b/newfile ansible localhost -m copy -a "src=/tmp/src/ dest=/tmp/dest/ remote_src=yes" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> `/tmp/src/a/b/newfile` copied to `/tmp/dest/a/b/newfile`, task marked as changed. ##### ACTUAL RESULTS `/tmp/dest/a/b/newfile` does not exist. Task marked as not changed. <!--- Paste verbatim command output between quotes --> ```paste below localhost | SUCCESS => { "changed": false, "checksum": null, "dest": "/tmp/dest/", "gid": 1269600003, "group": "akorsunsky", "md5sum": null, "mode": "0775", "owner": "akorsunsky", "size": 60, "src": "/tmp/src/", "state": "directory", "uid": 1269600003 } ```
https://github.com/ansible/ansible/issues/58284
https://github.com/ansible/ansible/pull/58323
26236f474ba8aa600d321c9cb7c5b11d123928ac
b7e38dfa52024c1363cdd37fac3fce52ad421f08
2019-06-24T15:11:09Z
python
2019-10-30T16:17:11Z
test/integration/targets/copy/tasks/tests.yml
# test code for the copy module and action plugin # (c) 2014, Michael DeHaan <[email protected]> # (c) 2017, Ansible Project # # GNU General Public License v3 or later (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt ) # - name: Record the output directory set_fact: remote_file: "{{ remote_dir }}/foo.txt" - name: Initiate a basic copy, and also test the mode copy: src: foo.txt dest: "{{ remote_file }}" mode: 0444 register: copy_result - name: Record the sha of the test file for later tests set_fact: remote_file_hash: "{{ copy_result['checksum'] }}" - name: Check the mode of the output file file: name: "{{ remote_file }}" state: file register: file_result_check - name: Assert the mode is correct assert: that: - "file_result_check.mode == '0444'" # same as expanduser & expandvars - command: 'echo {{ remote_dir }}' register: echo - set_fact: remote_dir_expanded: '{{ echo.stdout }}' remote_file_expanded: '{{ echo.stdout }}/foo.txt' - debug: var: copy_result verbosity: 1 - name: Assert basic copy worked assert: that: - "'changed' in copy_result" - copy_result.dest == remote_file_expanded - "'group' in copy_result" - "'gid' in copy_result" - "'checksum' in copy_result" - "'owner' in copy_result" - "'size' in copy_result" - "'src' in copy_result" - "'state' in copy_result" - "'uid' in copy_result" - name: Verify that the file was marked as changed assert: that: - "copy_result.changed == true" - name: Verify that the file checksums are correct assert: that: - "copy_result.checksum == ('foo.txt\n'|hash('sha1'))" - name: Verify that the legacy md5sum is correct assert: that: - "copy_result.md5sum == ('foo.txt\n'|hash('md5'))" when: ansible_fips|bool != True - name: Check the stat results of the file stat: path: "{{ remote_file }}" register: stat_results - debug: var: stat_results verbosity: 1 - name: Assert the stat results are correct assert: that: - "stat_results.stat.exists == true" - "stat_results.stat.isblk == false" - "stat_results.stat.isfifo == false" - "stat_results.stat.isreg == true" - "stat_results.stat.issock == false" - "stat_results.stat.checksum == ('foo.txt\n'|hash('sha1'))" - name: Overwrite the file via same means copy: src: foo.txt dest: "{{ remote_file }}" decrypt: no register: copy_result2 - name: Assert that the file was not changed assert: that: - "copy_result2 is not changed" - name: Assert basic copy worked assert: that: - "'changed' in copy_result2" - copy_result2.dest == remote_file_expanded - "'group' in copy_result2" - "'gid' in copy_result2" - "'checksum' in copy_result2" - "'owner' in copy_result2" - "'size' in copy_result2" - "'state' in copy_result2" - "'uid' in copy_result2" - name: Overwrite the file using the content system copy: content: "modified" dest: "{{ remote_file }}" decrypt: no register: copy_result3 - name: Check the stat results of the file stat: path: "{{ remote_file }}" register: stat_results - debug: var: stat_results verbosity: 1 - name: Assert that the file has changed assert: that: - "copy_result3 is changed" - "'content' not in copy_result3" - "stat_results.stat.checksum == ('modified'|hash('sha1'))" - "stat_results.stat.mode != '0700'" - name: Overwrite the file again using the content system, also passing along file params copy: content: "modified" dest: "{{ remote_file }}" mode: 0700 decrypt: no register: copy_result4 - name: Check the stat results of the file stat: path: "{{ remote_file }}" register: stat_results - debug: var: stat_results verbosity: 1 - name: Assert that the file has changed assert: that: - "copy_result3 is changed" - "'content' not in copy_result3" - "stat_results.stat.checksum == ('modified'|hash('sha1'))" - "stat_results.stat.mode == '0700'" - name: Create a hardlink to the file file: src: '{{ remote_file }}' dest: '{{ remote_dir }}/hard.lnk' state: hard - name: copy the same contents into place copy: content: 'modified' dest: '{{ remote_file }}' mode: 0700 decrypt: no register: copy_results - name: Check the stat results of the file stat: path: "{{ remote_file }}" register: stat_results - name: Check the stat results of the hard link stat: path: "{{ remote_dir }}/hard.lnk" register: hlink_results - name: Check that the file did not change assert: that: - 'stat_results.stat.inode == hlink_results.stat.inode' - 'copy_results.changed == False' - "stat_results.stat.checksum == ('modified'|hash('sha1'))" - name: copy the same contents into place but change mode copy: content: 'modified' dest: '{{ remote_file }}' mode: 0404 decrypt: no register: copy_results - name: Check the stat results of the file stat: path: "{{ remote_file }}" register: stat_results - name: Check the stat results of the hard link stat: path: "{{ remote_dir }}/hard.lnk" register: hlink_results - name: Check that the file changed permissions but is still the same assert: that: - 'stat_results.stat.inode == hlink_results.stat.inode' - 'copy_results.changed == True' - 'stat_results.stat.mode == hlink_results.stat.mode' - 'stat_results.stat.mode == "0404"' - "stat_results.stat.checksum == ('modified'|hash('sha1'))" - name: copy the different contents into place copy: content: 'adjusted' dest: '{{ remote_file }}' mode: 0404 register: copy_results - name: Check the stat results of the file stat: path: "{{ remote_file }}" register: stat_results - name: Check the stat results of the hard link stat: path: "{{ remote_dir }}/hard.lnk" register: hlink_results - name: Check that the file changed and hardlink was broken assert: that: - 'stat_results.stat.inode != hlink_results.stat.inode' - 'copy_results.changed == True' - "stat_results.stat.checksum == ('adjusted'|hash('sha1'))" - "hlink_results.stat.checksum == ('modified'|hash('sha1'))" - name: Try invalid copy input location fails copy: src: invalid_file_location_does_not_exist dest: "{{ remote_dir }}/file.txt" ignore_errors: True register: failed_copy - name: Assert that invalid source failed assert: that: - "failed_copy.failed" - "'invalid_file_location_does_not_exist' in failed_copy.msg" - name: Try empty source to ensure it fails copy: src: '' dest: "{{ remote_dir }}" ignore_errors: True register: failed_copy - debug: var: failed_copy verbosity: 1 - name: Assert that empty source failed assert: that: - failed_copy is failed - "'src (or content) is required' in failed_copy.msg" - name: Try without destination to ensure it fails copy: src: foo.txt ignore_errors: True register: failed_copy - debug: var: failed_copy verbosity: 1 - name: Assert that missing destination failed assert: that: - failed_copy is failed - "'dest is required' in failed_copy.msg" - name: Try without source to ensure it fails copy: dest: "{{ remote_file }}" ignore_errors: True register: failed_copy - debug: var: failed_copy verbosity: 1 - name: Assert that missing source failed assert: that: - failed_copy is failed - "'src (or content) is required' in failed_copy.msg" - name: Try with both src and content to ensure it fails copy: src: foo.txt content: testing dest: "{{ remote_file }}" ignore_errors: True register: failed_copy - name: Assert that mutually exclusive parameters failed assert: that: - failed_copy is failed - "'mutually exclusive' in failed_copy.msg" - name: Try with content and directory as destination to ensure it fails copy: content: testing dest: "{{ remote_dir }}" ignore_errors: True register: failed_copy - debug: var: failed_copy verbosity: 1 - name: Assert that content and directory as destination failed assert: that: - failed_copy is failed - "'can not use content with a dir as dest' in failed_copy.msg" - name: Clean up file: path: "{{ remote_file }}" state: absent - name: Copy source file to destination directory with mode copy: src: foo.txt dest: "{{ remote_dir }}" mode: 0500 register: copy_results - name: Check the stat results of the file stat: path: '{{ remote_file }}' register: stat_results - debug: var: stat_results verbosity: 1 - name: Assert that the file has changed assert: that: - "copy_results is changed" - "stat_results.stat.checksum == ('foo.txt\n'|hash('sha1'))" - "stat_results.stat.mode == '0500'" # Test copy with mode=preserve - name: Create file and set perms to an odd value copy: content: "foo.txt\n" dest: '{{ local_temp_dir }}/foo.txt' mode: 0547 delegate_to: localhost - name: Copy with mode=preserve copy: src: '{{ local_temp_dir }}/foo.txt' dest: '{{ remote_dir }}/copy-foo.txt' mode: preserve register: copy_results - name: Check the stat results of the file stat: path: '{{ remote_dir }}/copy-foo.txt' register: stat_results - name: Assert that the file has changed and has correct mode assert: that: - "copy_results is changed" - "copy_results.mode == '0547'" - "stat_results.stat.checksum == ('foo.txt\n'|hash('sha1'))" - "stat_results.stat.mode == '0547'" - name: Test copy with mode=preserve and remote_src=True copy: src: '{{ remote_dir }}/copy-foo.txt' dest: '{{ remote_dir }}/copy-foo2.txt' mode: 'preserve' remote_src: True register: copy_results2 - name: Check the stat results of the file stat: path: '{{ remote_dir }}/copy-foo2.txt' register: stat_results2 - name: Assert that the file has changed and has correct mode assert: that: - "copy_results2 is changed" - "copy_results2.mode == '0547'" - "stat_results2.stat.checksum == ('foo.txt\n'|hash('sha1'))" - "stat_results2.stat.mode == '0547'" # # test recursive copy local_follow=False, no trailing slash # - name: Create empty directory in the role we're copying from (git can't store empty dirs) file: path: '{{ role_path }}/files/subdir/subdira' state: directory delegate_to: localhost - name: Set the output subdirectory set_fact: remote_subdir: "{{ remote_dir }}/sub" - name: Make an output subdirectory file: name: "{{ remote_subdir }}" state: directory - name: Setup link target for absolute link copy: dest: /tmp/ansible-test-abs-link content: target delegate_to: localhost - name: Setup link target dir for absolute link file: dest: /tmp/ansible-test-abs-link-dir state: directory delegate_to: localhost - name: Test recursive copy to directory no trailing slash, local_follow=False copy: src: subdir dest: "{{ remote_subdir }}" directory_mode: 0700 local_follow: False register: recursive_copy_result - debug: var: recursive_copy_result verbosity: 1 - name: Assert that the recursive copy did something assert: that: - "recursive_copy_result is changed" - name: Check that a file in a directory was transferred stat: path: "{{ remote_dir }}/sub/subdir/bar.txt" register: stat_bar - name: Check that a file in a deeper directory was transferred stat: path: "{{ remote_dir }}/sub/subdir/subdir2/baz.txt" register: stat_bar2 - name: Check that a file in a directory whose parent contains a directory alone was transferred stat: path: "{{ remote_dir }}/sub/subdir/subdir2/subdir3/subdir4/qux.txt" register: stat_bar3 - name: Assert recursive copy files assert: that: - "stat_bar.stat.exists" - "stat_bar2.stat.exists" - "stat_bar3.stat.exists" - name: Check symlink to absolute path stat: path: '{{ remote_dir }}/sub/subdir/subdir1/ansible-test-abs-link' register: stat_abs_link - name: Check symlink to relative path stat: path: '{{ remote_dir }}/sub/subdir/subdir1/bar.txt' register: stat_relative_link - name: Check symlink to self stat: path: '{{ remote_dir }}/sub/subdir/subdir1/invalid' register: stat_self_link - name: Check symlink to nonexistent file stat: path: '{{ remote_dir }}/sub/subdir/subdir1/invalid2' register: stat_invalid_link - name: Check symlink to directory in copy stat: path: '{{ remote_dir }}/sub/subdir/subdir1/subdir3' register: stat_dir_in_copy_link - name: Check symlink to directory outside of copy stat: path: '{{ remote_dir }}/sub/subdir/subdir1/ansible-test-abs-link-dir' register: stat_dir_outside_copy_link - name: Assert recursive copy symlinks local_follow=False assert: that: - "stat_abs_link.stat.exists" - "stat_abs_link.stat.islnk" - "'/tmp/ansible-test-abs-link' == stat_abs_link.stat.lnk_target" - "stat_relative_link.stat.exists" - "stat_relative_link.stat.islnk" - "'../bar.txt' == stat_relative_link.stat.lnk_target" - "stat_self_link.stat.exists" - "stat_self_link.stat.islnk" - "'invalid' in stat_self_link.stat.lnk_target" - "stat_invalid_link.stat.exists" - "stat_invalid_link.stat.islnk" - "'../invalid' in stat_invalid_link.stat.lnk_target" - "stat_dir_in_copy_link.stat.exists" - "stat_dir_in_copy_link.stat.islnk" - "'../subdir2/subdir3' in stat_dir_in_copy_link.stat.lnk_target" - "stat_dir_outside_copy_link.stat.exists" - "stat_dir_outside_copy_link.stat.islnk" - "'/tmp/ansible-test-abs-link-dir' == stat_dir_outside_copy_link.stat.lnk_target" - name: Stat the recursively copied directories stat: path: "{{ remote_dir }}/sub/{{ item }}" register: dir_stats with_items: - "subdir" - "subdir/subdira" - "subdir/subdir1" - "subdir/subdir2" - "subdir/subdir2/subdir3" - "subdir/subdir2/subdir3/subdir4" - debug: var: stat_results verbosity: 1 - name: Assert recursive copied directories mode (1) assert: that: - "item.stat.exists" - "item.stat.mode == '0700'" with_items: "{{dir_stats.results}}" - name: Test recursive copy to directory no trailing slash, local_follow=False second time copy: src: subdir dest: "{{ remote_subdir }}" directory_mode: 0700 local_follow: False register: recursive_copy_result - name: Assert that the second copy did not change anything assert: that: - "recursive_copy_result is not changed" - name: Cleanup the recursive copy subdir file: name: "{{ remote_subdir }}" state: absent # # Recursive copy with local_follow=False, trailing slash # - name: Set the output subdirectory set_fact: remote_subdir: "{{ remote_dir }}/sub" - name: Make an output subdirectory file: name: "{{ remote_subdir }}" state: directory - name: Setup link target for absolute link copy: dest: /tmp/ansible-test-abs-link content: target delegate_to: localhost - name: Setup link target dir for absolute link file: dest: /tmp/ansible-test-abs-link-dir state: directory delegate_to: localhost - name: Test recursive copy to directory trailing slash, local_follow=False copy: src: subdir/ dest: "{{ remote_subdir }}" directory_mode: 0700 local_follow: False register: recursive_copy_result - debug: var: recursive_copy_result verbosity: 1 - name: Assert that the recursive copy did something assert: that: - "recursive_copy_result is changed" - name: Check that a file in a directory was transferred stat: path: "{{ remote_dir }}/sub/bar.txt" register: stat_bar - name: Check that a file in a deeper directory was transferred stat: path: "{{ remote_dir }}/sub/subdir2/baz.txt" register: stat_bar2 - name: Check that a file in a directory whose parent contains a directory alone was transferred stat: path: "{{ remote_dir }}/sub/subdir2/subdir3/subdir4/qux.txt" register: stat_bar3 - name: Assert recursive copy files assert: that: - "stat_bar.stat.exists" - "stat_bar2.stat.exists" - "stat_bar3.stat.exists" - name: Check symlink to absolute path stat: path: '{{ remote_dir }}/sub/subdir1/ansible-test-abs-link' register: stat_abs_link - name: Check symlink to relative path stat: path: '{{ remote_dir }}/sub/subdir1/bar.txt' register: stat_relative_link - name: Check symlink to self stat: path: '{{ remote_dir }}/sub/subdir1/invalid' register: stat_self_link - name: Check symlink to nonexistent file stat: path: '{{ remote_dir }}/sub/subdir1/invalid2' register: stat_invalid_link - name: Check symlink to directory in copy stat: path: '{{ remote_dir }}/sub/subdir1/subdir3' register: stat_dir_in_copy_link - name: Check symlink to directory outside of copy stat: path: '{{ remote_dir }}/sub/subdir1/ansible-test-abs-link-dir' register: stat_dir_outside_copy_link - name: Assert recursive copy symlinks local_follow=False trailing slash assert: that: - "stat_abs_link.stat.exists" - "stat_abs_link.stat.islnk" - "'/tmp/ansible-test-abs-link' == stat_abs_link.stat.lnk_target" - "stat_relative_link.stat.exists" - "stat_relative_link.stat.islnk" - "'../bar.txt' == stat_relative_link.stat.lnk_target" - "stat_self_link.stat.exists" - "stat_self_link.stat.islnk" - "'invalid' in stat_self_link.stat.lnk_target" - "stat_invalid_link.stat.exists" - "stat_invalid_link.stat.islnk" - "'../invalid' in stat_invalid_link.stat.lnk_target" - "stat_dir_in_copy_link.stat.exists" - "stat_dir_in_copy_link.stat.islnk" - "'../subdir2/subdir3' in stat_dir_in_copy_link.stat.lnk_target" - "stat_dir_outside_copy_link.stat.exists" - "stat_dir_outside_copy_link.stat.islnk" - "'/tmp/ansible-test-abs-link-dir' == stat_dir_outside_copy_link.stat.lnk_target" - name: Stat the recursively copied directories stat: path: "{{ remote_dir }}/sub/{{ item }}" register: dir_stats with_items: - "subdira" - "subdir1" - "subdir2" - "subdir2/subdir3" - "subdir2/subdir3/subdir4" - debug: var: dir_stats verbosity: 1 - name: Assert recursive copied directories mode (2) assert: that: - "item.stat.mode == '0700'" with_items: "{{dir_stats.results}}" - name: Test recursive copy to directory trailing slash, local_follow=False second time copy: src: subdir/ dest: "{{ remote_subdir }}" directory_mode: 0700 local_follow: False register: recursive_copy_result - name: Assert that the second copy did not change anything assert: that: - "recursive_copy_result is not changed" - name: Cleanup the recursive copy subdir file: name: "{{ remote_subdir }}" state: absent # # test recursive copy local_follow=True, no trailing slash # - name: Set the output subdirectory set_fact: remote_subdir: "{{ remote_dir }}/sub" - name: Make an output subdirectory file: name: "{{ remote_subdir }}" state: directory - name: Setup link target for absolute link copy: dest: /tmp/ansible-test-abs-link content: target delegate_to: localhost - name: Setup link target dir for absolute link file: dest: /tmp/ansible-test-abs-link-dir state: directory delegate_to: localhost - name: Test recursive copy to directory no trailing slash, local_follow=True copy: src: subdir dest: "{{ remote_subdir }}" directory_mode: 0700 local_follow: True register: recursive_copy_result - debug: var: recursive_copy_result verbosity: 1 - name: Assert that the recursive copy did something assert: that: - "recursive_copy_result is changed" - name: Check that a file in a directory was transferred stat: path: "{{ remote_dir }}/sub/subdir/bar.txt" register: stat_bar - name: Check that a file in a deeper directory was transferred stat: path: "{{ remote_dir }}/sub/subdir/subdir2/baz.txt" register: stat_bar2 - name: Check that a file in a directory whose parent contains a directory alone was transferred stat: path: "{{ remote_dir }}/sub/subdir/subdir2/subdir3/subdir4/qux.txt" register: stat_bar3 - name: Check that a file in a directory whose parent is a symlink was transferred stat: path: "{{ remote_dir }}/sub/subdir/subdir1/subdir3/subdir4/qux.txt" register: stat_bar4 - name: Assert recursive copy files assert: that: - "stat_bar.stat.exists" - "stat_bar2.stat.exists" - "stat_bar3.stat.exists" - "stat_bar4.stat.exists" - name: Check symlink to absolute path stat: path: '{{ remote_dir }}/sub/subdir/subdir1/ansible-test-abs-link' register: stat_abs_link - name: Check symlink to relative path stat: path: '{{ remote_dir }}/sub/subdir/subdir1/bar.txt' register: stat_relative_link - name: Check symlink to self stat: path: '{{ remote_dir }}/sub/subdir/subdir1/invalid' register: stat_self_link - name: Check symlink to nonexistent file stat: path: '{{ remote_dir }}/sub/subdir/subdir1/invalid2' register: stat_invalid_link - name: Check symlink to directory in copy stat: path: '{{ remote_dir }}/sub/subdir/subdir1/subdir3' register: stat_dir_in_copy_link - name: Check symlink to directory outside of copy stat: path: '{{ remote_dir }}/sub/subdir/subdir1/ansible-test-abs-link-dir' register: stat_dir_outside_copy_link - name: Assert recursive copy symlinks local_follow=True assert: that: - "stat_abs_link.stat.exists" - "not stat_abs_link.stat.islnk" - "stat_abs_link.stat.checksum == ('target'|hash('sha1'))" - "stat_relative_link.stat.exists" - "not stat_relative_link.stat.islnk" - "stat_relative_link.stat.checksum == ('baz\n'|hash('sha1'))" - "stat_self_link.stat.exists" - "stat_self_link.stat.islnk" - "'invalid' in stat_self_link.stat.lnk_target" - "stat_invalid_link.stat.exists" - "stat_invalid_link.stat.islnk" - "'../invalid' in stat_invalid_link.stat.lnk_target" - "stat_dir_in_copy_link.stat.exists" - "not stat_dir_in_copy_link.stat.islnk" - "stat_dir_in_copy_link.stat.isdir" - - "stat_dir_outside_copy_link.stat.exists" - "not stat_dir_outside_copy_link.stat.islnk" - "stat_dir_outside_copy_link.stat.isdir" - name: Stat the recursively copied directories stat: path: "{{ remote_dir }}/sub/{{ item }}" register: dir_stats with_items: - "subdir" - "subdir/subdira" - "subdir/subdir1" - "subdir/subdir1/subdir3" - "subdir/subdir1/subdir3/subdir4" - "subdir/subdir2" - "subdir/subdir2/subdir3" - "subdir/subdir2/subdir3/subdir4" - debug: var: dir_stats verbosity: 1 - name: Assert recursive copied directories mode (3) assert: that: - "item.stat.mode == '0700'" with_items: "{{dir_stats.results}}" - name: Test recursive copy to directory no trailing slash, local_follow=True second time copy: src: subdir dest: "{{ remote_subdir }}" directory_mode: 0700 local_follow: True register: recursive_copy_result - name: Assert that the second copy did not change anything assert: that: - "recursive_copy_result is not changed" - name: Cleanup the recursive copy subdir file: name: "{{ remote_subdir }}" state: absent # # Recursive copy of tricky symlinks # - block: - name: Create a directory to copy from file: path: '{{ local_temp_dir }}/source1' state: directory - name: Create a directory outside of the tree file: path: '{{ local_temp_dir }}/source2' state: directory - name: Create a symlink to a directory outside of the tree file: path: '{{ local_temp_dir }}/source1/link' src: '{{ local_temp_dir }}/source2' state: link - name: Create a circular link back to the tree file: path: '{{ local_temp_dir }}/source2/circle' src: '../source1' state: link - name: Create output directory file: path: '{{ local_temp_dir }}/dest1' state: directory delegate_to: localhost - name: Recursive copy the source copy: src: '{{ local_temp_dir }}/source1' dest: '{{ remote_dir }}/dest1' local_follow: True register: copy_result - name: Check that the tree link is now a directory stat: path: '{{ remote_dir }}/dest1/source1/link' register: link_result - name: Check that the out of tree link is still a link stat: path: '{{ remote_dir }}/dest1/source1/link/circle' register: circle_result - name: Verify that the recursive copy worked assert: that: - 'copy_result.changed' - 'link_result.stat.isdir' - 'not link_result.stat.islnk' - 'circle_result.stat.islnk' - '"../source1" == circle_result.stat.lnk_target' - name: Recursive copy the source a second time copy: src: '{{ local_temp_dir }}/source1' dest: '{{ remote_dir }}/dest1' local_follow: True register: copy_result - name: Verify that the recursive copy made no changes assert: that: - 'not copy_result.changed' # # Recursive copy with absolute paths (#27439) # - name: Test that remote_dir is appropriate for this test (absolute path) assert: that: - '{{ remote_dir_expanded[0] == "/" }}' - block: - name: Create a directory to copy file: path: '{{ local_temp_dir }}/source_recursive' state: directory - name: Create a file inside of the directory copy: content: "testing" dest: '{{ local_temp_dir }}/source_recursive/file' - name: Create a directory to place the test output in file: path: '{{ local_temp_dir }}/destination' state: directory delegate_to: localhost - name: Copy the directory and files within (no trailing slash) copy: src: '{{ local_temp_dir }}/source_recursive' dest: '{{ remote_dir }}/destination' - name: Stat the recursively copied directory stat: path: "{{ remote_dir }}/destination/{{ item }}" register: copied_stat with_items: - "source_recursive" - "source_recursive/file" - "file" - debug: var: copied_stat verbosity: 1 - name: Assert with no trailing slash, directory and file is copied assert: that: - "copied_stat.results[0].stat.exists" - "copied_stat.results[1].stat.exists" - "not copied_stat.results[2].stat.exists" - name: Cleanup file: path: '{{ remote_dir }}/destination' state: absent # Try again with no trailing slash - name: Create a directory to place the test output in file: path: '{{ remote_dir }}/destination' state: directory - name: Copy just the files inside of the directory copy: src: '{{ local_temp_dir }}/source_recursive/' dest: '{{ remote_dir }}/destination' - name: Stat the recursively copied directory stat: path: "{{ remote_dir }}/destination/{{ item }}" register: copied_stat with_items: - "source_recursive" - "source_recursive/file" - "file" - debug: var: copied_stat verbosity: 1 - name: Assert with trailing slash, only the file is copied assert: that: - "not copied_stat.results[0].stat.exists" - "not copied_stat.results[1].stat.exists" - "copied_stat.results[2].stat.exists" # # Recursive copy with relative paths (#34893) # - name: Create a directory to copy file: path: 'source_recursive' state: directory delegate_to: localhost - name: Create a file inside of the directory copy: content: "testing" dest: 'source_recursive/file' delegate_to: localhost - name: Create a directory to place the test output in file: path: 'destination' state: directory delegate_to: localhost - name: Copy the directory and files within (no trailing slash) copy: src: 'source_recursive' dest: 'destination' - name: Stat the recursively copied directory stat: path: "destination/{{ item }}" register: copied_stat with_items: - "source_recursive" - "source_recursive/file" - "file" - debug: var: copied_stat verbosity: 1 - name: Assert with no trailing slash, directory and file is copied assert: that: - "copied_stat.results[0].stat.exists" - "copied_stat.results[1].stat.exists" - "not copied_stat.results[2].stat.exists" - name: Cleanup file: path: 'destination' state: absent # Try again with no trailing slash - name: Create a directory to place the test output in file: path: 'destination' state: directory - name: Copy just the files inside of the directory copy: src: 'source_recursive/' dest: 'destination' - name: Stat the recursively copied directory stat: path: "destination/{{ item }}" register: copied_stat with_items: - "source_recursive" - "source_recursive/file" - "file" - debug: var: copied_stat verbosity: 1 - name: Assert with trailing slash, only the file is copied assert: that: - "not copied_stat.results[0].stat.exists" - "not copied_stat.results[1].stat.exists" - "copied_stat.results[2].stat.exists" - name: Cleanup file: path: 'destination' state: absent - name: Cleanup file: path: 'source_recursive' state: absent # # issue 8394 # - name: Create a file with content and a literal multiline block copy: content: | this is the first line this is the second line this line is after an empty line this line is the last line dest: "{{ remote_dir }}/multiline.txt" register: copy_result6 - debug: var: copy_result6 verbosity: 1 - name: Assert the multiline file was created correctly assert: that: - "copy_result6.changed" - "copy_result6.dest == '{{remote_dir_expanded}}/multiline.txt'" - "copy_result6.checksum == '9cd0697c6a9ff6689f0afb9136fa62e0b3fee903'" # test overwriting a file as an unprivileged user (pull request #8624) # this can't be relative to {{remote_dir}} as ~root usually has mode 700 - block: - name: Create world writable directory file: dest: /tmp/worldwritable state: directory mode: 0777 - name: Create world writable file copy: dest: /tmp/worldwritable/file.txt content: "bar" mode: 0666 - name: Overwrite the file as user nobody copy: dest: /tmp/worldwritable/file.txt content: "baz" become: yes become_user: nobody register: copy_result7 - name: Assert the file was overwritten assert: that: - "copy_result7.changed" - "copy_result7.dest == '/tmp/worldwritable/file.txt'" - "copy_result7.checksum == ('baz'|hash('sha1'))" - name: Clean up file: dest: /tmp/worldwritable state: absent remote_user: root # # Follow=True tests # # test overwriting a link using "follow=yes" so that the link # is preserved and the link target is updated - name: Create a test file to symlink to copy: dest: "{{ remote_dir }}/follow_test" content: "this is the follow test file\n" - name: Create a symlink to the test file file: path: "{{ remote_dir }}/follow_link" src: './follow_test' state: link - name: Update the test file using follow=True to preserve the link copy: dest: "{{ remote_dir }}/follow_link" src: foo.txt follow: yes register: replace_follow_result - name: Stat the link path stat: path: "{{ remote_dir }}/follow_link" register: stat_link_result - name: Assert that the link is still a link and contents were changed assert: that: - stat_link_result['stat']['islnk'] - stat_link_result['stat']['lnk_target'] == './follow_test' - replace_follow_result['changed'] - "replace_follow_result['checksum'] == remote_file_hash" # Symlink handling when the dest is already there # https://github.com/ansible/ansible-modules-core/issues/1568 - name: test idempotency by trying to copy to the symlink with the same contents copy: dest: "{{ remote_dir }}/follow_link" src: foo.txt follow: yes register: replace_follow_result - name: Stat the link path stat: path: "{{ remote_dir }}/follow_link" register: stat_link_result - name: Assert that the link is still a link and contents were changed assert: that: - stat_link_result['stat']['islnk'] - stat_link_result['stat']['lnk_target'] == './follow_test' - not replace_follow_result['changed'] - replace_follow_result['checksum'] == remote_file_hash - name: Update the test file using follow=False to overwrite the link copy: dest: '{{ remote_dir }}/follow_link' content: 'modified' follow: False register: copy_results - name: Check the stat results of the file stat: path: '{{remote_dir}}/follow_link' register: stat_results - debug: var: stat_results verbosity: 1 - name: Assert that the file has changed and is not a link assert: that: - "copy_results is changed" - "'content' not in copy_results" - "stat_results.stat.checksum == ('modified'|hash('sha1'))" - "not stat_results.stat.islnk" # test overwriting a link using "follow=yes" so that the link # is preserved and the link target is updated when the thing being copied is a link # # File mode tests # - name: setup directory for test file: state=directory dest={{remote_dir }}/directory mode=0755 - name: set file mode when the destination is a directory copy: src=foo.txt dest={{remote_dir}}/directory/ mode=0705 - name: set file mode when the destination is a directory copy: src=foo.txt dest={{remote_dir}}/directory/ mode=0604 register: file_result - name: check that the file has the correct attributes stat: path={{ remote_dir }}/directory/foo.txt register: file_attrs - assert: that: - "file_attrs.stat.mode == '0604'" # The below assertions make an invalid assumption, these were not explicitly set # - "file_attrs.stat.uid == 0" # - "file_attrs.stat.pw_name == 'root'" - name: check that the containing directory did not change attributes stat: path={{ remote_dir }}/directory/ register: dir_attrs - assert: that: - "dir_attrs.stat.mode == '0755'" # # I believe the below section is now covered in the recursive copying section. # Hold on for now as an original test case but delete once confirmed that # everything is passing # # Recursive copying with symlinks tests # - delegate_to: localhost block: - name: Create a test dir to copy file: path: '{{ local_temp_dir }}/top_dir' state: directory - name: Create a test dir to symlink to file: path: '{{ local_temp_dir }}/linked_dir' state: directory - name: Create a file in the test dir copy: dest: '{{ local_temp_dir }}/linked_dir/file1' content: 'hello world' - name: Create a link to the test dir file: path: '{{ local_temp_dir }}/top_dir/follow_link_dir' src: '{{ local_temp_dir }}/linked_dir' state: link - name: Create a circular subdir file: path: '{{ local_temp_dir }}/top_dir/subdir' state: directory ### FIXME: Also add a test for a relative symlink - name: Create a circular symlink file: path: '{{ local_temp_dir }}/top_dir/subdir/circle' src: '{{ local_temp_dir }}/top_dir/' state: link - name: Copy the directory's link copy: src: '{{ local_temp_dir }}/top_dir' dest: '{{ remote_dir }}/new_dir' local_follow: True - name: Stat the copied path stat: path: '{{ remote_dir }}/new_dir/top_dir/follow_link_dir' register: stat_dir_result - name: Stat the copied file stat: path: '{{ remote_dir }}/new_dir/top_dir/follow_link_dir/file1' register: stat_file_in_dir_result - name: Stat the circular symlink stat: path: '{{ remote_dir }}/new_dir/top_dir/subdir/circle' register: stat_circular_symlink_result - name: Assert that the directory exists assert: that: - stat_dir_result.stat.exists - stat_dir_result.stat.isdir - stat_file_in_dir_result.stat.exists - stat_file_in_dir_result.stat.isreg - stat_circular_symlink_result.stat.exists - stat_circular_symlink_result.stat.islnk # Relative paths in dest: - name: Smoketest that copying content to an implicit relative path works copy: content: 'testing' dest: 'ansible-testing.txt' register: relative_results - name: Assert that copying to an implicit relative path reported changed assert: that: - 'relative_results["changed"]' - 'relative_results["checksum"] == "dc724af18fbdd4e59189f5fe768a5f8311527050"' - name: Test that copying the same content with an implicit relative path reports no change copy: content: 'testing' dest: 'ansible-testing.txt' register: relative_results - name: Assert that copying the same content with an implicit relative path reports no change assert: that: - 'not relative_results["changed"]' - 'relative_results["checksum"] == "dc724af18fbdd4e59189f5fe768a5f8311527050"' - name: Test that copying different content with an implicit relative path reports change copy: content: 'testing2' dest: 'ansible-testing.txt' register: relative_results - name: Assert that copying different content with an implicit relative path reports changed assert: that: - 'relative_results["changed"]' - 'relative_results["checksum"] == "596b29ec9afea9e461a20610d150939b9c399d93"' - name: Smoketest that explicit relative path works copy: content: 'testing' dest: './ansible-testing.txt' register: relative_results - name: Assert that explicit relative paths reports change assert: that: - 'relative_results["changed"]' - 'relative_results["checksum"] == "dc724af18fbdd4e59189f5fe768a5f8311527050"' - name: Cleanup relative path tests file: path: 'ansible-testing.txt' state: absent # src is a file, dest is a non-existent directory (2 levels of directories): # checks that dest is created - include: dest_in_non_existent_directories.yml with_items: - { src: 'foo.txt', dest: 'new_sub_dir1/sub_dir2/', check: 'new_sub_dir1/sub_dir2/foo.txt' } - { src: 'subdir', dest: 'new_sub_dir1/sub_dir2/', check: 'new_sub_dir1/sub_dir2/subdir/bar.txt' } - { src: 'subdir/', dest: 'new_sub_dir1/sub_dir2/', check: 'new_sub_dir1/sub_dir2/bar.txt' } - { src: 'subdir', dest: 'new_sub_dir1/sub_dir2', check: 'new_sub_dir1/sub_dir2/subdir/bar.txt' } - { src: 'subdir/', dest: 'new_sub_dir1/sub_dir2', check: 'new_sub_dir1/sub_dir2/bar.txt' } # src is a file, dest is file in a non-existent directory: checks that a failure occurs - include: src_file_dest_file_in_non_existent_dir.yml with_items: - 'new_sub_dir1/sub_dir2/foo.txt' - 'new_sub_dir1/foo.txt' loop_control: loop_var: 'dest' # # Recursive copying on remote host # ## prepare for test - block: - name: execute - Create a test src dir file: path: '{{ remote_dir }}/remote_dir_src' state: directory - name: gather - Stat the remote_dir_src stat: path: '{{ remote_dir }}/remote_dir_src' register: stat_remote_dir_src_before - name: execute - Create a subdir file: path: '{{ remote_dir }}/remote_dir_src/subdir' state: directory - name: gather - Stat the remote_dir_src/subdir stat: path: '{{ remote_dir }}/remote_dir_src/subdir' register: stat_remote_dir_src_subdir_before - name: execute - Create a file in the top of src copy: dest: '{{ remote_dir }}/remote_dir_src/file1' content: 'hello world 1' - name: gather - Stat the remote_dir_src/file1 stat: path: '{{ remote_dir }}/remote_dir_src/file1' register: stat_remote_dir_src_file1_before - name: execute - Create a file in the subdir copy: dest: '{{ remote_dir }}/remote_dir_src/subdir/file12' content: 'hello world 12' - name: gather - Stat the remote_dir_src/subdir/file12 stat: path: '{{ remote_dir }}/remote_dir_src/subdir/file12' register: stat_remote_dir_src_subdir_file12_before - name: execute - Create a link to the file12 file: path: '{{ remote_dir }}/remote_dir_src/link_file12' src: '{{ remote_dir }}/remote_dir_src/subdir/file12' state: link - name: gather - Stat the remote_dir_src/link_file12 stat: path: '{{ remote_dir }}/remote_dir_src/link_file12' register: stat_remote_dir_src_link_file12_before ### test when src endswith os.sep and dest isdir - block: ### local_follow: True - name: execute - Create a test dest dir file: path: '{{ remote_dir }}/testcase1_local_follow_true' state: directory - name: execute - Copy the directory on remote with local_follow True copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src/' dest: '{{ remote_dir }}/testcase1_local_follow_true' local_follow: True register: testcase1 - name: gather - Stat the testcase1_local_follow_true stat: path: '{{ remote_dir }}/testcase1_local_follow_true' register: stat_testcase1_local_follow_true - name: gather - Stat the testcase1_local_follow_true/subdir stat: path: '{{ remote_dir }}/testcase1_local_follow_true/subdir' register: stat_testcase1_local_follow_true_subdir - name: gather - Stat the testcase1_local_follow_true/file1 stat: path: '{{ remote_dir }}/testcase1_local_follow_true/file1' register: stat_testcase1_local_follow_true_file1 - name: gather - Stat the testcase1_local_follow_true/subdir/file12 stat: path: '{{ remote_dir }}/testcase1_local_follow_true/subdir/file12' register: stat_testcase1_local_follow_true_subdir_file12 - name: gather - Stat the testcase1_local_follow_true/link_file12 stat: path: '{{ remote_dir }}/testcase1_local_follow_true/link_file12' register: stat_testcase1_local_follow_true_link_file12 - name: assert - remote_dir_src has copied with local_follow True. assert: that: - testcase1 is changed - "stat_testcase1_local_follow_true.stat.isdir" - "stat_testcase1_local_follow_true_subdir.stat.isdir" - "stat_testcase1_local_follow_true_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase1_local_follow_true_file1.stat.checksum" - "stat_testcase1_local_follow_true_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase1_local_follow_true_subdir_file12.stat.checksum" - "stat_testcase1_local_follow_true_link_file12.stat.exists" - "not stat_testcase1_local_follow_true_link_file12.stat.islnk" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase1_local_follow_true_link_file12.stat.checksum" ### local_follow: False - name: execute - Create a test dest dir file: path: '{{ remote_dir }}/testcase1_local_follow_false' state: directory - name: execute - Copy the directory on remote with local_follow False copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src/' dest: '{{ remote_dir }}/testcase1_local_follow_false' local_follow: False register: testcase1 - name: gather - Stat the testcase1_local_follow_false stat: path: '{{ remote_dir }}/testcase1_local_follow_false' register: stat_testcase1_local_follow_false - name: gather - Stat the testcase1_local_follow_false/subdir stat: path: '{{ remote_dir }}/testcase1_local_follow_false/subdir' register: stat_testcase1_local_follow_false_subdir - name: gather - Stat the testcase1_local_follow_false/file1 stat: path: '{{ remote_dir }}/testcase1_local_follow_false/file1' register: stat_testcase1_local_follow_false_file1 - name: gather - Stat the testcase1_local_follow_false/subdir/file12 stat: path: '{{ remote_dir }}/testcase1_local_follow_false/subdir/file12' register: stat_testcase1_local_follow_false_subdir_file12 - name: gather - Stat the testcase1_local_follow_false/link_file12 stat: path: '{{ remote_dir }}/testcase1_local_follow_false/link_file12' register: stat_testcase1_local_follow_false_link_file12 - name: assert - remote_dir_src has copied with local_follow True. assert: that: - testcase1 is changed - "stat_testcase1_local_follow_false.stat.isdir" - "stat_testcase1_local_follow_false_subdir.stat.isdir" - "stat_testcase1_local_follow_false_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase1_local_follow_false_file1.stat.checksum" - "stat_testcase1_local_follow_false_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase1_local_follow_false_subdir_file12.stat.checksum" - "stat_testcase1_local_follow_false_link_file12.stat.exists" - "stat_testcase1_local_follow_false_link_file12.stat.islnk" ## test when src endswith os.sep and dest not exists - block: - name: execute - Copy the directory on remote with local_follow True copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src/' dest: '{{ remote_dir }}/testcase2_local_follow_true' local_follow: True register: testcase2 - name: gather - Stat the testcase2_local_follow_true stat: path: '{{ remote_dir }}/testcase2_local_follow_true' register: stat_testcase2_local_follow_true - name: gather - Stat the testcase2_local_follow_true/subdir stat: path: '{{ remote_dir }}/testcase2_local_follow_true/subdir' register: stat_testcase2_local_follow_true_subdir - name: gather - Stat the testcase2_local_follow_true/file1 stat: path: '{{ remote_dir }}/testcase2_local_follow_true/file1' register: stat_testcase2_local_follow_true_file1 - name: gather - Stat the testcase2_local_follow_true/subdir/file12 stat: path: '{{ remote_dir }}/testcase2_local_follow_true/subdir/file12' register: stat_testcase2_local_follow_true_subdir_file12 - name: gather - Stat the testcase2_local_follow_true/link_file12 stat: path: '{{ remote_dir }}/testcase2_local_follow_true/link_file12' register: stat_testcase2_local_follow_true_link_file12 - name: assert - remote_dir_src has copied with local_follow True. assert: that: - testcase2 is changed - "stat_testcase2_local_follow_true.stat.isdir" - "stat_testcase2_local_follow_true_subdir.stat.isdir" - "stat_testcase2_local_follow_true_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase2_local_follow_true_file1.stat.checksum" - "stat_testcase2_local_follow_true_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase2_local_follow_true_subdir_file12.stat.checksum" - "stat_testcase2_local_follow_true_link_file12.stat.exists" - "not stat_testcase2_local_follow_true_link_file12.stat.islnk" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase2_local_follow_true_link_file12.stat.checksum" ### local_follow: False - name: execute - Copy the directory on remote with local_follow False copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src/' dest: '{{ remote_dir }}/testcase2_local_follow_false' local_follow: False register: testcase2 - name: execute - Copy the directory on remote with local_follow False copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src/' dest: '{{ remote_dir }}/testcase2_local_follow_false' local_follow: False register: testcase1 - name: gather - Stat the testcase2_local_follow_false stat: path: '{{ remote_dir }}/testcase2_local_follow_false' register: stat_testcase2_local_follow_false - name: gather - Stat the testcase2_local_follow_false/subdir stat: path: '{{ remote_dir }}/testcase2_local_follow_false/subdir' register: stat_testcase2_local_follow_false_subdir - name: gather - Stat the testcase2_local_follow_false/file1 stat: path: '{{ remote_dir }}/testcase2_local_follow_false/file1' register: stat_testcase2_local_follow_false_file1 - name: gather - Stat the testcase2_local_follow_false/subdir/file12 stat: path: '{{ remote_dir }}/testcase2_local_follow_false/subdir/file12' register: stat_testcase2_local_follow_false_subdir_file12 - name: gather - Stat the testcase2_local_follow_false/link_file12 stat: path: '{{ remote_dir }}/testcase2_local_follow_false/link_file12' register: stat_testcase2_local_follow_false_link_file12 - name: assert - remote_dir_src has copied with local_follow True. assert: that: - testcase2 is changed - "stat_testcase2_local_follow_false.stat.isdir" - "stat_testcase2_local_follow_false_subdir.stat.isdir" - "stat_testcase2_local_follow_false_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase2_local_follow_false_file1.stat.checksum" - "stat_testcase2_local_follow_false_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase2_local_follow_false_subdir_file12.stat.checksum" - "stat_testcase2_local_follow_false_link_file12.stat.exists" - "stat_testcase2_local_follow_false_link_file12.stat.islnk" ## test when src not endswith os.sep and dest isdir - block: ### local_follow: True - name: execute - Create a test dest dir file: path: '{{ remote_dir }}/testcase3_local_follow_true' state: directory - name: execute - Copy the directory on remote with local_follow True copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src' dest: '{{ remote_dir }}/testcase3_local_follow_true' local_follow: True register: testcase3 - name: gather - Stat the testcase3_local_follow_true stat: path: '{{ remote_dir }}/testcase3_local_follow_true/remote_dir_src' register: stat_testcase3_local_follow_true_remote_dir_src - name: gather - Stat the testcase3_local_follow_true/remote_dir_src/subdir stat: path: '{{ remote_dir }}/testcase3_local_follow_true/remote_dir_src/subdir' register: stat_testcase3_local_follow_true_remote_dir_src_subdir - name: gather - Stat the testcase3_local_follow_true/remote_dir_src/file1 stat: path: '{{ remote_dir }}/testcase3_local_follow_true/remote_dir_src/file1' register: stat_testcase3_local_follow_true_remote_dir_src_file1 - name: gather - Stat the testcase3_local_follow_true/remote_dir_src/subdir/file12 stat: path: '{{ remote_dir }}/testcase3_local_follow_true/remote_dir_src/subdir/file12' register: stat_testcase3_local_follow_true_remote_dir_src_subdir_file12 - name: gather - Stat the testcase3_local_follow_true/remote_dir_src/link_file12 stat: path: '{{ remote_dir }}/testcase3_local_follow_true/remote_dir_src/link_file12' register: stat_testcase3_local_follow_true_remote_dir_src_link_file12 - name: assert - remote_dir_src has copied with local_follow True. assert: that: - testcase3 is changed - "stat_testcase3_local_follow_true_remote_dir_src.stat.isdir" - "stat_testcase3_local_follow_true_remote_dir_src_subdir.stat.isdir" - "stat_testcase3_local_follow_true_remote_dir_src_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase3_local_follow_true_remote_dir_src_file1.stat.checksum" - "stat_testcase3_local_follow_true_remote_dir_src_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase3_local_follow_true_remote_dir_src_subdir_file12.stat.checksum" - "stat_testcase3_local_follow_true_remote_dir_src_link_file12.stat.exists" - "not stat_testcase3_local_follow_true_remote_dir_src_link_file12.stat.islnk" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase3_local_follow_true_remote_dir_src_link_file12.stat.checksum" ### local_follow: False - name: execute - Create a test dest dir file: path: '{{ remote_dir }}/testcase3_local_follow_false' state: directory - name: execute - Copy the directory on remote with local_follow False copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src' dest: '{{ remote_dir }}/testcase3_local_follow_false' local_follow: False register: testcase3 - name: gather - Stat the testcase3_local_follow_false stat: path: '{{ remote_dir }}/testcase3_local_follow_false/remote_dir_src' register: stat_testcase3_local_follow_false_remote_dir_src - name: gather - Stat the testcase3_local_follow_false/remote_dir_src/subdir stat: path: '{{ remote_dir }}/testcase3_local_follow_false/remote_dir_src/subdir' register: stat_testcase3_local_follow_false_remote_dir_src_subdir - name: gather - Stat the testcase3_local_follow_false/remote_dir_src/file1 stat: path: '{{ remote_dir }}/testcase3_local_follow_false/remote_dir_src/file1' register: stat_testcase3_local_follow_false_remote_dir_src_file1 - name: gather - Stat the testcase3_local_follow_false/remote_dir_src/subdir/file12 stat: path: '{{ remote_dir }}/testcase3_local_follow_false/remote_dir_src/subdir/file12' register: stat_testcase3_local_follow_false_remote_dir_src_subdir_file12 - name: gather - Stat the testcase3_local_follow_false/remote_dir_src/link_file12 stat: path: '{{ remote_dir }}/testcase3_local_follow_false/remote_dir_src/link_file12' register: stat_testcase3_local_follow_false_remote_dir_src_link_file12 - name: assert - remote_dir_src has copied with local_follow False. assert: that: - testcase3 is changed - "stat_testcase3_local_follow_false_remote_dir_src.stat.isdir" - "stat_testcase3_local_follow_false_remote_dir_src_subdir.stat.isdir" - "stat_testcase3_local_follow_false_remote_dir_src_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase3_local_follow_false_remote_dir_src_file1.stat.checksum" - "stat_testcase3_local_follow_false_remote_dir_src_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase3_local_follow_false_remote_dir_src_subdir_file12.stat.checksum" - "stat_testcase3_local_follow_false_remote_dir_src_link_file12.stat.exists" - "stat_testcase3_local_follow_false_remote_dir_src_link_file12.stat.islnk" ## test when src not endswith os.sep and dest not exists - block: ### local_follow: True - name: execute - Copy the directory on remote with local_follow True copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src' dest: '{{ remote_dir }}/testcase4_local_follow_true' local_follow: True register: testcase4 - name: gather - Stat the testcase4_local_follow_true stat: path: '{{ remote_dir }}/testcase4_local_follow_true/remote_dir_src' register: stat_testcase4_local_follow_true_remote_dir_src - name: gather - Stat the testcase4_local_follow_true/remote_dir_src/subdir stat: path: '{{ remote_dir }}/testcase4_local_follow_true/remote_dir_src/subdir' register: stat_testcase4_local_follow_true_remote_dir_src_subdir - name: gather - Stat the testcase4_local_follow_true/remote_dir_src/file1 stat: path: '{{ remote_dir }}/testcase4_local_follow_true/remote_dir_src/file1' register: stat_testcase4_local_follow_true_remote_dir_src_file1 - name: gather - Stat the testcase4_local_follow_true/remote_dir_src/subdir/file12 stat: path: '{{ remote_dir }}/testcase4_local_follow_true/remote_dir_src/subdir/file12' register: stat_testcase4_local_follow_true_remote_dir_src_subdir_file12 - name: gather - Stat the testcase4_local_follow_true/remote_dir_src/link_file12 stat: path: '{{ remote_dir }}/testcase4_local_follow_true/remote_dir_src/link_file12' register: stat_testcase4_local_follow_true_remote_dir_src_link_file12 - name: assert - remote_dir_src has copied with local_follow True. assert: that: - testcase4 is changed - "stat_testcase4_local_follow_true_remote_dir_src.stat.isdir" - "stat_testcase4_local_follow_true_remote_dir_src_subdir.stat.isdir" - "stat_testcase4_local_follow_true_remote_dir_src_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase4_local_follow_true_remote_dir_src_file1.stat.checksum" - "stat_testcase4_local_follow_true_remote_dir_src_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase4_local_follow_true_remote_dir_src_subdir_file12.stat.checksum" - "stat_testcase4_local_follow_true_remote_dir_src_link_file12.stat.exists" - "not stat_testcase4_local_follow_true_remote_dir_src_link_file12.stat.islnk" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase4_local_follow_true_remote_dir_src_link_file12.stat.checksum" ### local_follow: False - name: execute - Copy the directory on remote with local_follow False copy: remote_src: True src: '{{ remote_dir }}/remote_dir_src' dest: '{{ remote_dir }}/testcase4_local_follow_false' local_follow: False register: testcase4 - name: gather - Stat the testcase4_local_follow_false stat: path: '{{ remote_dir }}/testcase4_local_follow_false/remote_dir_src' register: stat_testcase4_local_follow_false_remote_dir_src - name: gather - Stat the testcase4_local_follow_false/remote_dir_src/subdir stat: path: '{{ remote_dir }}/testcase4_local_follow_false/remote_dir_src/subdir' register: stat_testcase4_local_follow_false_remote_dir_src_subdir - name: gather - Stat the testcase4_local_follow_false/remote_dir_src/file1 stat: path: '{{ remote_dir }}/testcase4_local_follow_false/remote_dir_src/file1' register: stat_testcase4_local_follow_false_remote_dir_src_file1 - name: gather - Stat the testcase4_local_follow_false/remote_dir_src/subdir/file12 stat: path: '{{ remote_dir }}/testcase4_local_follow_false/remote_dir_src/subdir/file12' register: stat_testcase4_local_follow_false_remote_dir_src_subdir_file12 - name: gather - Stat the testcase4_local_follow_false/remote_dir_src/link_file12 stat: path: '{{ remote_dir }}/testcase4_local_follow_false/remote_dir_src/link_file12' register: stat_testcase4_local_follow_false_remote_dir_src_link_file12 - name: assert - remote_dir_src has copied with local_follow False. assert: that: - testcase4 is changed - "stat_testcase4_local_follow_false_remote_dir_src.stat.isdir" - "stat_testcase4_local_follow_false_remote_dir_src_subdir.stat.isdir" - "stat_testcase4_local_follow_false_remote_dir_src_file1.stat.exists" - "stat_remote_dir_src_file1_before.stat.checksum == stat_testcase4_local_follow_false_remote_dir_src_file1.stat.checksum" - "stat_testcase4_local_follow_false_remote_dir_src_subdir_file12.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_testcase4_local_follow_false_remote_dir_src_subdir_file12.stat.checksum" - "stat_testcase4_local_follow_false_remote_dir_src_link_file12.stat.exists" - "stat_testcase4_local_follow_false_remote_dir_src_link_file12.stat.islnk" ## test copying the directory on remote with chown - block: - set_fact: ansible_copy_test_user_name: 'ansible_copy_test_{{ 100000 | random }}' - name: execute - create a user for test user: name: '{{ ansible_copy_test_user_name }}' state: present become: true register: ansible_copy_test_user - name: execute - create a group for test group: name: '{{ ansible_copy_test_user_name }}' state: present become: true register: ansible_copy_test_group - name: execute - Copy the directory on remote with chown copy: remote_src: True src: '{{ remote_dir_expanded }}/remote_dir_src/' dest: '{{ remote_dir_expanded }}/new_dir_with_chown' owner: '{{ ansible_copy_test_user_name }}' group: '{{ ansible_copy_test_user_name }}' follow: true register: testcase5 become: true - name: gather - Stat the new_dir_with_chown stat: path: '{{ remote_dir }}/new_dir_with_chown' register: stat_new_dir_with_chown - name: gather - Stat the new_dir_with_chown/file1 stat: path: '{{ remote_dir }}/new_dir_with_chown/file1' register: stat_new_dir_with_chown_file1 - name: gather - Stat the new_dir_with_chown/subdir stat: path: '{{ remote_dir }}/new_dir_with_chown/subdir' register: stat_new_dir_with_chown_subdir - name: gather - Stat the new_dir_with_chown/subdir/file12 stat: path: '{{ remote_dir }}/new_dir_with_chown/subdir/file12' register: stat_new_dir_with_chown_subdir_file12 - name: gather - Stat the new_dir_with_chown/link_file12 stat: path: '{{ remote_dir }}/new_dir_with_chown/link_file12' register: stat_new_dir_with_chown_link_file12 - name: assert - owner and group have changed assert: that: - testcase5 is changed - "stat_new_dir_with_chown.stat.uid == {{ ansible_copy_test_user.uid }}" - "stat_new_dir_with_chown.stat.gid == {{ ansible_copy_test_group.gid }}" - "stat_new_dir_with_chown.stat.pw_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown.stat.gr_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_file1.stat.uid == {{ ansible_copy_test_user.uid }}" - "stat_new_dir_with_chown_file1.stat.gid == {{ ansible_copy_test_group.gid }}" - "stat_new_dir_with_chown_file1.stat.pw_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_file1.stat.gr_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_subdir.stat.uid == {{ ansible_copy_test_user.uid }}" - "stat_new_dir_with_chown_subdir.stat.gid == {{ ansible_copy_test_group.gid }}" - "stat_new_dir_with_chown_subdir.stat.pw_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_subdir.stat.gr_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_subdir_file12.stat.uid == {{ ansible_copy_test_user.uid }}" - "stat_new_dir_with_chown_subdir_file12.stat.gid == {{ ansible_copy_test_group.gid }}" - "stat_new_dir_with_chown_subdir_file12.stat.pw_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_subdir_file12.stat.gr_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_link_file12.stat.uid == {{ ansible_copy_test_user.uid }}" - "stat_new_dir_with_chown_link_file12.stat.gid == {{ ansible_copy_test_group.gid }}" - "stat_new_dir_with_chown_link_file12.stat.pw_name == '{{ ansible_copy_test_user_name }}'" - "stat_new_dir_with_chown_link_file12.stat.gr_name == '{{ ansible_copy_test_user_name }}'" always: - name: execute - remove the user for test user: name: '{{ ansible_copy_test_user_name }}' state: absent remove: yes become: true - name: execute - remove the group for test group: name: '{{ ansible_copy_test_user_name }}' state: absent become: true ## testcase last - make sure remote_dir_src not change - block: - name: Stat the remote_dir_src stat: path: '{{ remote_dir }}/remote_dir_src' register: stat_remote_dir_src_after - name: Stat the remote_dir_src/subdir stat: path: '{{ remote_dir }}/remote_dir_src/subdir' register: stat_remote_dir_src_subdir_after - name: Stat the remote_dir_src/file1 stat: path: '{{ remote_dir }}/remote_dir_src/file1' register: stat_remote_dir_src_file1_after - name: Stat the remote_dir_src/subdir/file12 stat: path: '{{ remote_dir }}/remote_dir_src/subdir/file12' register: stat_remote_dir_src_subdir_file12_after - name: Stat the remote_dir_src/link_file12 stat: path: '{{ remote_dir }}/remote_dir_src/link_file12' register: stat_remote_dir_src_link_file12_after - name: Assert that remote_dir_src not change. assert: that: - "stat_remote_dir_src_after.stat.exists" - "stat_remote_dir_src_after.stat.isdir" - "stat_remote_dir_src_before.stat.uid == stat_remote_dir_src_after.stat.uid" - "stat_remote_dir_src_before.stat.gid == stat_remote_dir_src_after.stat.gid" - "stat_remote_dir_src_before.stat.pw_name == stat_remote_dir_src_after.stat.pw_name" - "stat_remote_dir_src_before.stat.gr_name == stat_remote_dir_src_after.stat.gr_name" - "stat_remote_dir_src_before.stat.path == stat_remote_dir_src_after.stat.path" - "stat_remote_dir_src_before.stat.mode == stat_remote_dir_src_after.stat.mode" - "stat_remote_dir_src_subdir_after.stat.exists" - "stat_remote_dir_src_subdir_after.stat.isdir" - "stat_remote_dir_src_subdir_before.stat.uid == stat_remote_dir_src_subdir_after.stat.uid" - "stat_remote_dir_src_subdir_before.stat.gid == stat_remote_dir_src_subdir_after.stat.gid" - "stat_remote_dir_src_subdir_before.stat.pw_name == stat_remote_dir_src_subdir_after.stat.pw_name" - "stat_remote_dir_src_subdir_before.stat.gr_name == stat_remote_dir_src_subdir_after.stat.gr_name" - "stat_remote_dir_src_subdir_before.stat.path == stat_remote_dir_src_subdir_after.stat.path" - "stat_remote_dir_src_subdir_before.stat.mode == stat_remote_dir_src_subdir_after.stat.mode" - "stat_remote_dir_src_file1_after.stat.exists" - "stat_remote_dir_src_file1_before.stat.uid == stat_remote_dir_src_file1_after.stat.uid" - "stat_remote_dir_src_file1_before.stat.gid == stat_remote_dir_src_file1_after.stat.gid" - "stat_remote_dir_src_file1_before.stat.pw_name == stat_remote_dir_src_file1_after.stat.pw_name" - "stat_remote_dir_src_file1_before.stat.gr_name == stat_remote_dir_src_file1_after.stat.gr_name" - "stat_remote_dir_src_file1_before.stat.path == stat_remote_dir_src_file1_after.stat.path" - "stat_remote_dir_src_file1_before.stat.mode == stat_remote_dir_src_file1_after.stat.mode" - "stat_remote_dir_src_file1_before.stat.checksum == stat_remote_dir_src_file1_after.stat.checksum" - "stat_remote_dir_src_subdir_file12_after.stat.exists" - "stat_remote_dir_src_subdir_file12_before.stat.uid == stat_remote_dir_src_subdir_file12_after.stat.uid" - "stat_remote_dir_src_subdir_file12_before.stat.gid == stat_remote_dir_src_subdir_file12_after.stat.gid" - "stat_remote_dir_src_subdir_file12_before.stat.pw_name == stat_remote_dir_src_subdir_file12_after.stat.pw_name" - "stat_remote_dir_src_subdir_file12_before.stat.gr_name == stat_remote_dir_src_subdir_file12_after.stat.gr_name" - "stat_remote_dir_src_subdir_file12_before.stat.path == stat_remote_dir_src_subdir_file12_after.stat.path" - "stat_remote_dir_src_subdir_file12_before.stat.mode == stat_remote_dir_src_subdir_file12_after.stat.mode" - "stat_remote_dir_src_subdir_file12_before.stat.checksum == stat_remote_dir_src_subdir_file12_after.stat.checksum" - "stat_remote_dir_src_link_file12_after.stat.exists" - "stat_remote_dir_src_link_file12_after.stat.islnk" - "stat_remote_dir_src_link_file12_before.stat.uid == stat_remote_dir_src_link_file12_after.stat.uid" - "stat_remote_dir_src_link_file12_before.stat.gid == stat_remote_dir_src_link_file12_after.stat.gid" - "stat_remote_dir_src_link_file12_before.stat.pw_name == stat_remote_dir_src_link_file12_after.stat.pw_name" - "stat_remote_dir_src_link_file12_before.stat.gr_name == stat_remote_dir_src_link_file12_after.stat.gr_name" - "stat_remote_dir_src_link_file12_before.stat.path == stat_remote_dir_src_link_file12_after.stat.path" - "stat_remote_dir_src_link_file12_before.stat.mode == stat_remote_dir_src_link_file12_after.stat.mode"
closed
ansible/ansible
https://github.com/ansible/ansible
63,412
Pull #47290 does not seem to have resolved ios priviledge 0 bug
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> Still receiving "unable to set terminal parameter for Cisco IOS devices with priviledge 0 user and become: yes configured ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> ios_command module ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.10.0.dev0 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/bryan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/bryan/.local/lib/python3.6/site-packages/ansible executable location = /home/bryan/.local/bin/ansible python version = 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below COLOR_VERBOSE(/etc/ansible/ansible.cfg) = red DEPRECATION_WARNINGS(/etc/ansible/ansible.cfg) = False HOST_KEY_CHECKING(/etc/ansible/ansible.cfg) = False ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Mix of Cisco IOS devices ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Any ios-related modules are failing due to broken priviledge escalation. This is with Ansible v2.8, v2.8.5 and devel 2.10.0. <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - name: Show Version hosts: all become: yes become_method: enable gather_facts: no # vars_files: # - vault.yml tasks: - name: Show Version ios_command: commands: "Show Version" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Priviledge escalation to work as expected ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> Fatal error: "msg": "unable to set terminal parameters" <!--- Paste verbatim command output between quotes --> ```paste below ansible-playbook 2.10.0.dev0 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/bryan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/bryan/.local/lib/python3.6/site-packages/ansible executable location = /home/bryan/.local/bin/ansible-playbook python version = 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] Using /etc/ansible/ansible.cfg as config file BECOME password: setting up inventory plugins host_list declined parsing /home/bryan/CoKAnsible/inventory as it did not pass its verify_file() method script declined parsing /home/bryan/CoKAnsible/inventory as it did not pass its verify_file() method auto declined parsing /home/bryan/CoKAnsible/inventory as it did not pass its verify_file() method Parsed /home/bryan/CoKAnsible/inventory inventory source with ini plugin Loading callback plugin default of type stdout, v2.0 from /home/bryan/.local/lib/python3.6/site-packages/ansible/plugins/callback/default.py PLAYBOOK: FirstPlay.yml **************************************************************************************************************************************************** Positional arguments: FirstPlay.yml verbosity: 4 connection: smart timeout: 10 become_method: sudo become_ask_pass: True tags: ('all',) inventory: ('/home/bryan/CoKAnsible/inventory',) subset: 172.16.225.253 forks: 5 1 plays in FirstPlay.yml PLAY [Show Version] ******************************************************************************************************************************************************** META: ran handlers TASK [Show Version] ******************************************************************************************************************************************************** task path: /home/bryan/CoKAnsible/FirstPlay.yml:11 <172.16.225.253> attempting to start connection <172.16.225.253> using connection plugin network_cli Found ansible-connection at path /home/bryan/.local/bin/ansible-connection <172.16.225.253> local domain socket does not exist, starting it <172.16.225.253> control socket path is /home/bryan/.ansible/pc/6ea8c00d6e <172.16.225.253> local domain socket listeners started successfully <172.16.225.253> loaded cliconf plugin for network_os ios <172.16.225.253> <172.16.225.253> local domain socket path is /home/bryan/.ansible/pc/6ea8c00d6e fatal: [172.16.225.253]: FAILED! => { "changed": false, "msg": "unable to set terminal parameters" } PLAY RECAP ***************************************************************************************************************************************************************** 172.16.225.253 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/63412
https://github.com/ansible/ansible/pull/63571
0a384601764814f9f8b1731e01d1bcbdca2c9b37
0cd2ad588032ac1d15ca7084c5c03c91e607a80a
2019-10-11T23:57:18Z
python
2019-10-30T20:10:36Z
lib/ansible/plugins/connection/network_cli.py
# (c) 2016 Red Hat Inc. # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ --- author: Ansible Networking Team connection: network_cli short_description: Use network_cli to run command on network appliances description: - This connection plugin provides a connection to remote devices over the SSH and implements a CLI shell. This connection plugin is typically used by network devices for sending and receiving CLi commands to network devices. version_added: "2.3" options: host: description: - Specifies the remote device FQDN or IP address to establish the SSH connection to. default: inventory_hostname vars: - name: ansible_host port: type: int description: - Specifies the port on the remote device that listens for connections when establishing the SSH connection. default: 22 ini: - section: defaults key: remote_port env: - name: ANSIBLE_REMOTE_PORT vars: - name: ansible_port network_os: description: - Configures the device platform network operating system. This value is used to load the correct terminal and cliconf plugins to communicate with the remote device. vars: - name: ansible_network_os remote_user: description: - The username used to authenticate to the remote device when the SSH connection is first established. If the remote_user is not specified, the connection will use the username of the logged in user. - Can be configured from the CLI via the C(--user) or C(-u) options. ini: - section: defaults key: remote_user env: - name: ANSIBLE_REMOTE_USER vars: - name: ansible_user password: description: - Configures the user password used to authenticate to the remote device when first establishing the SSH connection. vars: - name: ansible_password - name: ansible_ssh_pass - name: ansible_ssh_password private_key_file: description: - The private SSH key or certificate file used to authenticate to the remote device when first establishing the SSH connection. ini: - section: defaults key: private_key_file env: - name: ANSIBLE_PRIVATE_KEY_FILE vars: - name: ansible_private_key_file timeout: type: int description: - Sets the connection time, in seconds, for communicating with the remote device. This timeout is used as the default timeout value for commands when issuing a command to the network CLI. If the command does not return in timeout seconds, an error is generated. default: 120 become: type: boolean description: - The become option will instruct the CLI session to attempt privilege escalation on platforms that support it. Normally this means transitioning from user mode to C(enable) mode in the CLI session. If become is set to True and the remote device does not support privilege escalation or the privilege has already been elevated, then this option is silently ignored. - Can be configured from the CLI via the C(--become) or C(-b) options. default: False ini: - section: privilege_escalation key: become env: - name: ANSIBLE_BECOME vars: - name: ansible_become become_method: description: - This option allows the become method to be specified in for handling privilege escalation. Typically the become_method value is set to C(enable) but could be defined as other values. default: sudo ini: - section: privilege_escalation key: become_method env: - name: ANSIBLE_BECOME_METHOD vars: - name: ansible_become_method host_key_auto_add: type: boolean description: - By default, Ansible will prompt the user before adding SSH keys to the known hosts file. Since persistent connections such as network_cli run in background processes, the user will never be prompted. By enabling this option, unknown host keys will automatically be added to the known hosts file. - Be sure to fully understand the security implications of enabling this option on production systems as it could create a security vulnerability. default: False ini: - section: paramiko_connection key: host_key_auto_add env: - name: ANSIBLE_HOST_KEY_AUTO_ADD persistent_connect_timeout: type: int description: - Configures, in seconds, the amount of time to wait when trying to initially establish a persistent connection. If this value expires before the connection to the remote device is completed, the connection will fail. default: 30 ini: - section: persistent_connection key: connect_timeout env: - name: ANSIBLE_PERSISTENT_CONNECT_TIMEOUT vars: - name: ansible_connect_timeout persistent_command_timeout: type: int description: - Configures, in seconds, the amount of time to wait for a command to return from the remote device. If this timer is exceeded before the command returns, the connection plugin will raise an exception and close. default: 30 ini: - section: persistent_connection key: command_timeout env: - name: ANSIBLE_PERSISTENT_COMMAND_TIMEOUT vars: - name: ansible_command_timeout persistent_buffer_read_timeout: type: float description: - Configures, in seconds, the amount of time to wait for the data to be read from Paramiko channel after the command prompt is matched. This timeout value ensures that command prompt matched is correct and there is no more data left to be received from remote host. default: 0.1 ini: - section: persistent_connection key: buffer_read_timeout env: - name: ANSIBLE_PERSISTENT_BUFFER_READ_TIMEOUT vars: - name: ansible_buffer_read_timeout persistent_log_messages: type: boolean description: - This flag will enable logging the command executed and response received from target device in the ansible log file. For this option to work 'log_path' ansible configuration option is required to be set to a file path with write access. - Be sure to fully understand the security implications of enabling this option as it could create a security vulnerability by logging sensitive information in log file. default: False ini: - section: persistent_connection key: log_messages env: - name: ANSIBLE_PERSISTENT_LOG_MESSAGES vars: - name: ansible_persistent_log_messages terminal_stdout_re: type: list elements: dict version_added: '2.9' description: - A single regex pattern or a sequence of patterns along with optional flags to match the command prompt from the received response chunk. This option accepts C(pattern) and C(flags) keys. The value of C(pattern) is a python regex pattern to match the response and the value of C(flags) is the value accepted by I(flags) argument of I(re.compile) python method to control the way regex is matched with the response, for example I('re.I'). vars: - name: ansible_terminal_stdout_re terminal_stderr_re: type: list elements: dict version_added: '2.9' description: - This option provides the regex pattern and optional flags to match the error string from the received response chunk. This option accepts C(pattern) and C(flags) keys. The value of C(pattern) is a python regex pattern to match the response and the value of C(flags) is the value accepted by I(flags) argument of I(re.compile) python method to control the way regex is matched with the response, for example I('re.I'). vars: - name: ansible_terminal_stderr_re terminal_initial_prompt: type: list version_added: '2.9' description: - A single regex pattern or a sequence of patterns to evaluate the expected prompt at the time of initial login to the remote host. vars: - name: ansible_terminal_initial_prompt terminal_initial_answer: type: list version_added: '2.9' description: - The answer to reply with if the C(terminal_initial_prompt) is matched. The value can be a single answer or a list of answers for multiple terminal_initial_prompt. In case the login menu has multiple prompts the sequence of the prompt and excepted answer should be in same order and the value of I(terminal_prompt_checkall) should be set to I(True) if all the values in C(terminal_initial_prompt) are expected to be matched and set to I(False) if any one login prompt is to be matched. vars: - name: ansible_terminal_initial_answer terminal_initial_prompt_checkall: type: boolean version_added: '2.9' description: - By default the value is set to I(False) and any one of the prompts mentioned in C(terminal_initial_prompt) option is matched it won't check for other prompts. When set to I(True) it will check for all the prompts mentioned in C(terminal_initial_prompt) option in the given order and all the prompts should be received from remote host if not it will result in timeout. default: False vars: - name: ansible_terminal_initial_prompt_checkall terminal_inital_prompt_newline: type: boolean version_added: '2.9' description: - This boolean flag, that when set to I(True) will send newline in the response if any of values in I(terminal_initial_prompt) is matched. default: True vars: - name: ansible_terminal_initial_prompt_newline network_cli_retries: description: - Number of attempts to connect to remote host. The delay time between the retires increases after every attempt by power of 2 in seconds till either the maximum attempts are exhausted or any of the C(persistent_command_timeout) or C(persistent_connect_timeout) timers are triggered. default: 3 version_added: '2.9' type: integer env: - name: ANSIBLE_NETWORK_CLI_RETRIES ini: - section: persistent_connection key: network_cli_retries vars: - name: ansible_network_cli_retries """ import getpass import json import logging import re import os import signal import socket import time import traceback from io import BytesIO from ansible.errors import AnsibleConnectionFailure from ansible.module_utils.six import PY3 from ansible.module_utils.six.moves import cPickle from ansible.module_utils.network.common.utils import to_list from ansible.module_utils._text import to_bytes, to_text from ansible.playbook.play_context import PlayContext from ansible.plugins.connection import NetworkConnectionBase, ensure_connect from ansible.plugins.loader import cliconf_loader, terminal_loader, connection_loader class AnsibleCmdRespRecv(Exception): pass class Connection(NetworkConnectionBase): ''' CLI (shell) SSH connections on Paramiko ''' transport = 'network_cli' has_pipelining = True def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self._ssh_shell = None self._matched_prompt = None self._matched_cmd_prompt = None self._matched_pattern = None self._last_response = None self._history = list() self._command_response = None self._terminal = None self.cliconf = None self._paramiko_conn = None if self._play_context.verbosity > 3: logging.getLogger('paramiko').setLevel(logging.DEBUG) if self._network_os: self._terminal = terminal_loader.get(self._network_os, self) if not self._terminal: raise AnsibleConnectionFailure('network os %s is not supported' % self._network_os) self.cliconf = cliconf_loader.get(self._network_os, self) if self.cliconf: self.queue_message('vvvv', 'loaded cliconf plugin for network_os %s' % self._network_os) self._sub_plugin = {'type': 'cliconf', 'name': self._network_os, 'obj': self.cliconf} else: self.queue_message('vvvv', 'unable to load cliconf for network_os %s' % self._network_os) else: raise AnsibleConnectionFailure( 'Unable to automatically determine host network os. Please ' 'manually configure ansible_network_os value for this host' ) self.queue_message('log', 'network_os is set to %s' % self._network_os) @property def paramiko_conn(self): if self._paramiko_conn is None: self._paramiko_conn = connection_loader.get('paramiko', self._play_context, '/dev/null') self._paramiko_conn.set_options(direct={'look_for_keys': not bool(self._play_context.password and not self._play_context.private_key_file)}) return self._paramiko_conn def _get_log_channel(self): name = "p=%s u=%s | " % (os.getpid(), getpass.getuser()) name += "paramiko [%s]" % self._play_context.remote_addr return name @ensure_connect def get_prompt(self): """Returns the current prompt from the device""" return self._matched_prompt def exec_command(self, cmd, in_data=None, sudoable=True): # this try..except block is just to handle the transition to supporting # network_cli as a toplevel connection. Once connection=local is gone, # this block can be removed as well and all calls passed directly to # the local connection if self._ssh_shell: try: cmd = json.loads(to_text(cmd, errors='surrogate_or_strict')) kwargs = {'command': to_bytes(cmd['command'], errors='surrogate_or_strict')} for key in ('prompt', 'answer', 'sendonly', 'newline', 'prompt_retry_check'): if cmd.get(key) is True or cmd.get(key) is False: kwargs[key] = cmd[key] elif cmd.get(key) is not None: kwargs[key] = to_bytes(cmd[key], errors='surrogate_or_strict') return self.send(**kwargs) except ValueError: cmd = to_bytes(cmd, errors='surrogate_or_strict') return self.send(command=cmd) else: return super(Connection, self).exec_command(cmd, in_data, sudoable) def update_play_context(self, pc_data): """Updates the play context information for the connection""" pc_data = to_bytes(pc_data) if PY3: pc_data = cPickle.loads(pc_data, encoding='bytes') else: pc_data = cPickle.loads(pc_data) play_context = PlayContext() play_context.deserialize(pc_data) self.queue_message('vvvv', 'updating play_context for connection') if self._play_context.become ^ play_context.become: if play_context.become is True: auth_pass = play_context.become_pass self._terminal.on_become(passwd=auth_pass) self.queue_message('vvvv', 'authorizing connection') else: self._terminal.on_unbecome() self.queue_message('vvvv', 'deauthorizing connection') self._play_context = play_context if hasattr(self, 'reset_history'): self.reset_history() if hasattr(self, 'disable_response_logging'): self.disable_response_logging() def _connect(self): ''' Connects to the remote device and starts the terminal ''' if not self.connected: self.paramiko_conn._set_log_channel(self._get_log_channel()) self.paramiko_conn.force_persistence = self.force_persistence command_timeout = self.get_option('persistent_command_timeout') max_pause = min([self.get_option('persistent_connect_timeout'), command_timeout]) retries = self.get_option('network_cli_retries') total_pause = 0 for attempt in range(retries + 1): try: ssh = self.paramiko_conn._connect() break except Exception as e: pause = 2 ** (attempt + 1) if attempt == retries or total_pause >= max_pause: raise AnsibleConnectionFailure(to_text(e, errors='surrogate_or_strict')) else: msg = (u"network_cli_retry: attempt: %d, caught exception(%s), " u"pausing for %d seconds" % (attempt + 1, to_text(e, errors='surrogate_or_strict'), pause)) self.queue_message('vv', msg) time.sleep(pause) total_pause += pause continue self.queue_message('vvvv', 'ssh connection done, setting terminal') self._connected = True self._ssh_shell = ssh.ssh.invoke_shell() self._ssh_shell.settimeout(command_timeout) self.queue_message('vvvv', 'loaded terminal plugin for network_os %s' % self._network_os) terminal_initial_prompt = self.get_option('terminal_initial_prompt') or self._terminal.terminal_initial_prompt terminal_initial_answer = self.get_option('terminal_initial_answer') or self._terminal.terminal_initial_answer newline = self.get_option('terminal_inital_prompt_newline') or self._terminal.terminal_inital_prompt_newline check_all = self.get_option('terminal_initial_prompt_checkall') or False self.receive(prompts=terminal_initial_prompt, answer=terminal_initial_answer, newline=newline, check_all=check_all) self.queue_message('vvvv', 'firing event: on_open_shell()') self._terminal.on_open_shell() if self._play_context.become and self._play_context.become_method == 'enable': self.queue_message('vvvv', 'firing event: on_become') auth_pass = self._play_context.become_pass self._terminal.on_become(passwd=auth_pass) self.queue_message('vvvv', 'ssh connection has completed successfully') return self def close(self): ''' Close the active connection to the device ''' # only close the connection if its connected. if self._connected: self.queue_message('debug', "closing ssh connection to device") if self._ssh_shell: self.queue_message('debug', "firing event: on_close_shell()") self._terminal.on_close_shell() self._ssh_shell.close() self._ssh_shell = None self.queue_message('debug', "cli session is now closed") self.paramiko_conn.close() self._paramiko_conn = None self.queue_message('debug', "ssh connection has been closed successfully") super(Connection, self).close() def receive(self, command=None, prompts=None, answer=None, newline=True, prompt_retry_check=False, check_all=False): ''' Handles receiving of output from command ''' self._matched_prompt = None self._matched_cmd_prompt = None recv = BytesIO() handled = False command_prompt_matched = False matched_prompt_window = window_count = 0 # set terminal regex values for command prompt and errors in response self._terminal_stderr_re = self._get_terminal_std_re('terminal_stderr_re') self._terminal_stdout_re = self._get_terminal_std_re('terminal_stdout_re') cache_socket_timeout = self._ssh_shell.gettimeout() command_timeout = self.get_option('persistent_command_timeout') self._validate_timeout_value(command_timeout, "persistent_command_timeout") if cache_socket_timeout != command_timeout: self._ssh_shell.settimeout(command_timeout) buffer_read_timeout = self.get_option('persistent_buffer_read_timeout') self._validate_timeout_value(buffer_read_timeout, "persistent_buffer_read_timeout") self._log_messages("command: %s" % command) while True: if command_prompt_matched: try: signal.signal(signal.SIGALRM, self._handle_buffer_read_timeout) signal.setitimer(signal.ITIMER_REAL, buffer_read_timeout) data = self._ssh_shell.recv(256) signal.alarm(0) self._log_messages("response-%s: %s" % (window_count + 1, data)) # if data is still received on channel it indicates the prompt string # is wrongly matched in between response chunks, continue to read # remaining response. command_prompt_matched = False # restart command_timeout timer signal.signal(signal.SIGALRM, self._handle_command_timeout) signal.alarm(command_timeout) except AnsibleCmdRespRecv: # reset socket timeout to global timeout self._ssh_shell.settimeout(cache_socket_timeout) return self._command_response else: data = self._ssh_shell.recv(256) self._log_messages("response-%s: %s" % (window_count + 1, data)) # when a channel stream is closed, received data will be empty if not data: break recv.write(data) offset = recv.tell() - 256 if recv.tell() > 256 else 0 recv.seek(offset) window = self._strip(recv.read()) window_count += 1 if prompts and not handled: handled = self._handle_prompt(window, prompts, answer, newline, False, check_all) matched_prompt_window = window_count elif prompts and handled and prompt_retry_check and matched_prompt_window + 1 == window_count: # check again even when handled, if same prompt repeats in next window # (like in the case of a wrong enable password, etc) indicates # value of answer is wrong, report this as error. if self._handle_prompt(window, prompts, answer, newline, prompt_retry_check, check_all): raise AnsibleConnectionFailure("For matched prompt '%s', answer is not valid" % self._matched_cmd_prompt) if self._find_prompt(window): self._last_response = recv.getvalue() resp = self._strip(self._last_response) self._command_response = self._sanitize(resp, command) if buffer_read_timeout == 0.0: # reset socket timeout to global timeout self._ssh_shell.settimeout(cache_socket_timeout) return self._command_response else: command_prompt_matched = True @ensure_connect def send(self, command, prompt=None, answer=None, newline=True, sendonly=False, prompt_retry_check=False, check_all=False): ''' Sends the command to the device in the opened shell ''' if check_all: prompt_len = len(to_list(prompt)) answer_len = len(to_list(answer)) if prompt_len != answer_len: raise AnsibleConnectionFailure("Number of prompts (%s) is not same as that of answers (%s)" % (prompt_len, answer_len)) try: cmd = b'%s\r' % command self._history.append(cmd) self._ssh_shell.sendall(cmd) self._log_messages('send command: %s' % cmd) if sendonly: return response = self.receive(command, prompt, answer, newline, prompt_retry_check, check_all) return to_text(response, errors='surrogate_then_replace') except (socket.timeout, AttributeError): self.queue_message('error', traceback.format_exc()) raise AnsibleConnectionFailure("timeout value %s seconds reached while trying to send command: %s" % (self._ssh_shell.gettimeout(), command.strip())) def _handle_buffer_read_timeout(self, signum, frame): self.queue_message('vvvv', "Response received, triggered 'persistent_buffer_read_timeout' timer of %s seconds" % self.get_option('persistent_buffer_read_timeout')) raise AnsibleCmdRespRecv() def _handle_command_timeout(self, signum, frame): msg = 'command timeout triggered, timeout value is %s secs.\nSee the timeout setting options in the Network Debug and Troubleshooting Guide.'\ % self.get_option('persistent_command_timeout') self.queue_message('log', msg) raise AnsibleConnectionFailure(msg) def _strip(self, data): ''' Removes ANSI codes from device response ''' for regex in self._terminal.ansi_re: data = regex.sub(b'', data) return data def _handle_prompt(self, resp, prompts, answer, newline, prompt_retry_check=False, check_all=False): ''' Matches the command prompt and responds :arg resp: Byte string containing the raw response from the remote :arg prompts: Sequence of byte strings that we consider prompts for input :arg answer: Sequence of Byte string to send back to the remote if we find a prompt. A carriage return is automatically appended to this string. :param prompt_retry_check: Bool value for trying to detect more prompts :param check_all: Bool value to indicate if all the values in prompt sequence should be matched or any one of given prompt. :returns: True if a prompt was found in ``resp``. If check_all is True will True only after all the prompt in the prompts list are matched. False otherwise. ''' single_prompt = False if not isinstance(prompts, list): prompts = [prompts] single_prompt = True if not isinstance(answer, list): answer = [answer] prompts_regex = [re.compile(to_bytes(r), re.I) for r in prompts] for index, regex in enumerate(prompts_regex): match = regex.search(resp) if match: self._matched_cmd_prompt = match.group() self._log_messages("matched command prompt: %s" % self._matched_cmd_prompt) # if prompt_retry_check is enabled to check if same prompt is # repeated don't send answer again. if not prompt_retry_check: prompt_answer = answer[index] if len(answer) > index else answer[0] self._ssh_shell.sendall(b'%s' % prompt_answer) if newline: self._ssh_shell.sendall(b'\r') prompt_answer += b'\r' self._log_messages("matched command prompt answer: %s" % prompt_answer) if check_all and prompts and not single_prompt: prompts.pop(0) answer.pop(0) return False return True return False def _sanitize(self, resp, command=None): ''' Removes elements from the response before returning to the caller ''' cleaned = [] for line in resp.splitlines(): if command and line.strip() == command.strip(): continue for prompt in self._matched_prompt.strip().splitlines(): if prompt.strip() in line: break else: cleaned.append(line) return b'\n'.join(cleaned).strip() def _find_prompt(self, response): '''Searches the buffered response for a matching command prompt ''' errored_response = None is_error_message = False for regex in self._terminal_stderr_re: if regex.search(response): is_error_message = True # Check if error response ends with command prompt if not # receive it buffered prompt for regex in self._terminal_stdout_re: match = regex.search(response) if match: errored_response = response self._matched_pattern = regex.pattern self._matched_prompt = match.group() self._log_messages("matched error regex '%s' from response '%s'" % (self._matched_pattern, errored_response)) break if not is_error_message: for regex in self._terminal_stdout_re: match = regex.search(response) if match: self._matched_pattern = regex.pattern self._matched_prompt = match.group() self._log_messages("matched cli prompt '%s' with regex '%s' from response '%s'" % (self._matched_prompt, self._matched_pattern, response)) if not errored_response: return True if errored_response: raise AnsibleConnectionFailure(errored_response) return False def _validate_timeout_value(self, timeout, timer_name): if timeout < 0: raise AnsibleConnectionFailure("'%s' timer value '%s' is invalid, value should be greater than or equal to zero." % (timer_name, timeout)) def transport_test(self, connect_timeout): """This method enables wait_for_connection to work. As it is used by wait_for_connection, it is called by that module's action plugin, which is on the controller process, which means that nothing done on this instance should impact the actual persistent connection... this check is for informational purposes only and should be properly cleaned up. """ # Force a fresh connect if for some reason we have connected before. self.close() self._connect() self.close() def _get_terminal_std_re(self, option): terminal_std_option = self.get_option(option) terminal_std_re = [] if terminal_std_option: for item in terminal_std_option: if "pattern" not in item: raise AnsibleConnectionFailure("'pattern' is a required key for option '%s'," " received option value is %s" % (option, item)) pattern = br"%s" % to_bytes(item['pattern']) flag = item.get('flags', 0) if flag: flag = getattr(re, flag.split('.')[1]) terminal_std_re.append(re.compile(pattern, flag)) else: # To maintain backward compatibility terminal_std_re = getattr(self._terminal, option) return terminal_std_re
closed
ansible/ansible
https://github.com/ansible/ansible
62,819
redfish_info / redfish_config - Manager - GetManagerServices / SetManagerServices
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> This feature would implement a GetManagerServices command for the Manager category of redfish_info, to retrieve a list of NetworkProtocol and their properties, like SSH, Port, Enable or Disable. And also implement a SetManagerServices command for the Manager category of redfish_config, to set NetworkProtocol's properties, like enable/disable SSH, change Port. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_config ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> These 2 commands would help user to get the status of services or control the status of services Manager provided. <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/62819
https://github.com/ansible/ansible/pull/62815
4e8bb334a9da287bb31775db2e7f4e7318ec90ca
8316fa66e8a16fb15e16d18fdff001f6617d9ef4
2019-09-25T07:16:11Z
python
2019-10-31T07:57:20Z
lib/ansible/module_utils/redfish_utils.py
# Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import json from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import http_client from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} class RedfishUtils(object): def __init__(self, creds, root_uri, timeout, module): self.root_uri = root_uri self.creds = creds self.timeout = timeout self.module = module self.service_root = '/redfish/v1/' self._init_session() # The following functions are to send GET/POST/PATCH/DELETE requests def get_request(self, uri): try: resp = open_url(uri, method="GET", headers=GET_HEADERS, url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) data = json.loads(resp.read()) headers = dict((k.lower(), v) for (k, v) in resp.info().items()) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'data': data, 'headers': headers} def post_request(self, uri, pyld): try: resp = open_url(uri, data=json.dumps(pyld), headers=POST_HEADERS, method="POST", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def patch_request(self, uri, pyld): headers = PATCH_HEADERS r = self.get_request(uri) if r['ret']: # Get etag from etag header or @odata.etag property etag = r['headers'].get('etag') if not etag: etag = r['data'].get('@odata.etag') if etag: # Make copy of headers and add If-Match header headers = dict(headers) headers['If-Match'] = etag try: resp = open_url(uri, data=json.dumps(pyld), headers=headers, method="PATCH", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def delete_request(self, uri, pyld=None): try: data = json.dumps(pyld) if pyld else None resp = open_url(uri, data=data, headers=DELETE_HEADERS, method="DELETE", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} @staticmethod def _get_extended_message(error): """ Get Redfish ExtendedInfo message from response payload if present :param error: an HTTPError exception :type error: HTTPError :return: the ExtendedInfo message if present, else standard HTTP error """ msg = http_client.responses.get(error.code, '') if error.code >= 400: try: body = error.read().decode('utf-8') data = json.loads(body) ext_info = data['error']['@Message.ExtendedInfo'] msg = ext_info[0]['Message'] except Exception: pass return msg def _init_session(self): pass def _find_accountservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} else: account_service = data["AccountService"]["@odata.id"] response = self.get_request(self.root_uri + account_service) if response['ret'] is False: return response data = response['data'] accounts = data['Accounts']['@odata.id'] if accounts[-1:] == '/': accounts = accounts[:-1] self.accounts_uri = accounts return {'ret': True} def _find_sessionservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'SessionService' not in data: return {'ret': False, 'msg': "SessionService resource not found"} else: session_service = data["SessionService"]["@odata.id"] response = self.get_request(self.root_uri + session_service) if response['ret'] is False: return response data = response['data'] sessions = data['Sessions']['@odata.id'] if sessions[-1:] == '/': sessions = sessions[:-1] self.sessions_uri = sessions return {'ret': True} def _find_systems_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Systems' not in data: return {'ret': False, 'msg': "Systems resource not found"} response = self.get_request(self.root_uri + data['Systems']['@odata.id']) if response['ret'] is False: return response self.systems_uris = [ i['@odata.id'] for i in response['data'].get('Members', [])] if not self.systems_uris: return { 'ret': False, 'msg': "ComputerSystem's Members array is either empty or missing"} return {'ret': True} def _find_updateservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'UpdateService' not in data: return {'ret': False, 'msg': "UpdateService resource not found"} else: update = data["UpdateService"]["@odata.id"] self.update_uri = update response = self.get_request(self.root_uri + update) if response['ret'] is False: return response data = response['data'] self.firmware_uri = self.software_uri = None if 'FirmwareInventory' in data: self.firmware_uri = data['FirmwareInventory'][u'@odata.id'] if 'SoftwareInventory' in data: self.software_uri = data['SoftwareInventory'][u'@odata.id'] return {'ret': True} def _find_chassis_resource(self): chassis_service = [] response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Chassis' not in data: return {'ret': False, 'msg': "Chassis resource not found"} else: chassis = data["Chassis"]["@odata.id"] response = self.get_request(self.root_uri + chassis) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: chassis_service.append(member[u'@odata.id']) self.chassis_uri_list = chassis_service return {'ret': True} def _find_managers_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Managers' not in data: return {'ret': False, 'msg': "Manager resource not found"} else: manager = data["Managers"]["@odata.id"] response = self.get_request(self.root_uri + manager) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: manager_service = member[u'@odata.id'] self.manager_uri = manager_service return {'ret': True} def get_logs(self): log_svcs_uri_list = [] list_of_logs = [] properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat', 'Message', 'MessageId', 'MessageArgs'] # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data.get('Members', []): response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id']) if response['ret'] is False: return response _data = response['data'] if 'Entries' in _data: log_svcs_uri_list.append(_data['Entries'][u'@odata.id']) # For each entry in LogServices, get log name and all log entries for log_svcs_uri in log_svcs_uri_list: logs = {} list_of_log_entries = [] response = self.get_request(self.root_uri + log_svcs_uri) if response['ret'] is False: return response data = response['data'] logs['Description'] = data.get('Description', 'Collection of log entries') # Get all log entries for each type of log found for logEntry in data.get('Members', []): entry = {} for prop in properties: if prop in logEntry: entry[prop] = logEntry.get(prop) if entry: list_of_log_entries.append(entry) log_name = log_svcs_uri.split('/')[-1] logs[log_name] = list_of_log_entries list_of_logs.append(logs) # list_of_logs[logs{list_of_log_entries[entry{}]}] return {'ret': True, 'entries': list_of_logs} def clear_logs(self): # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data[u'Members']: response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"]) if response['ret'] is False: return response _data = response['data'] # Check to make sure option is available, otherwise error is ugly if "Actions" in _data: if "#LogService.ClearLog" in _data[u"Actions"]: self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {}) if response['ret'] is False: return response return {'ret': True} def aggregate(self, func): ret = True entries = [] for systems_uri in self.systems_uris: inventory = func(systems_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'systems_uri': systems_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_storage_controller_inventory(self, systems_uri): result = {} controller_list = [] controller_results = [] # Get these entries, but does not fail if not found properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers', 'Location', 'Manufacturer', 'Model', 'Name', 'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status'] key = "StorageControllers" # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'Storage' not in data: return {'ret': False, 'msg': "Storage resource not found"} # Get a list of all storage controllers and build respective URIs storage_uri = data['Storage']["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Loop through Members and their StorageControllers # and gather properties from each StorageController if data[u'Members']: for storage_member in data[u'Members']: storage_member_uri = storage_member[u'@odata.id'] response = self.get_request(self.root_uri + storage_member_uri) data = response['data'] if key in data: controller_list = data[key] for controller in controller_list: controller_result = {} for property in properties: if property in controller: controller_result[property] = controller[property] controller_results.append(controller_result) result['entries'] = controller_results return result else: return {'ret': False, 'msg': "Storage resource not found"} def get_multi_storage_controller_inventory(self): return self.aggregate(self.get_storage_controller_inventory) def get_disk_inventory(self, systems_uri): result = {'entries': []} controller_list = [] # Get these entries, but does not fail if not found properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes', 'EncryptionAbility', 'EncryptionStatus', 'FailurePredicted', 'HotspareType', 'Id', 'Identifiers', 'Manufacturer', 'MediaType', 'Model', 'Name', 'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision', 'RotationSpeedRPM', 'SerialNumber', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data[u'Members']: for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] if 'Drives' in data: for device in data[u'Drives']: disk_uri = self.root_uri + device[u'@odata.id'] response = self.get_request(disk_uri) data = response['data'] drive_result = {} for property in properties: if property in data: if data[property] is not None: drive_result[property] = data[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) if 'SimpleStorage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data["SimpleStorage"]["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Name' in data: controller_name = data['Name'] else: sc_id = data.get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] for device in data[u'Devices']: drive_result = {} for property in properties: if property in device: drive_result[property] = device[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) return result def get_multi_disk_inventory(self): return self.aggregate(self.get_disk_inventory) def get_volume_inventory(self, systems_uri): result = {'entries': []} controller_list = [] volume_list = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes', 'Capacity', 'CapacityBytes', 'CapacitySources', 'Encrypted', 'EncryptionTypes', 'Identifiers', 'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities', 'AllocatedPools', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data.get('Members'): for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id volume_results = [] if 'Volumes' in data: # Get a list of all volumes and build respective URIs volumes_uri = data[u'Volumes'][u'@odata.id'] response = self.get_request(self.root_uri + volumes_uri) data = response['data'] if data.get('Members'): for volume in data[u'Members']: volume_list.append(volume[u'@odata.id']) for v in volume_list: uri = self.root_uri + v response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] volume_result = {} for property in properties: if property in data: if data[property] is not None: volume_result[property] = data[property] # Get related Drives Id drive_id_list = [] if 'Links' in data: if 'Drives' in data[u'Links']: for link in data[u'Links'][u'Drives']: drive_id_link = link[u'@odata.id'] drive_id = drive_id_link.split("/")[-1] drive_id_list.append({'Id': drive_id}) volume_result['Linked_drives'] = drive_id_list volume_results.append(volume_result) volumes = {'Controller': controller_name, 'Volumes': volume_results} result["entries"].append(volumes) else: return {'ret': False, 'msg': "Storage resource not found"} return result def get_multi_volume_inventory(self): return self.aggregate(self.get_volume_inventory) def restart_manager_gracefully(self): result = {} key = "Actions" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] action_uri = data[key]["#Manager.Reset"]["target"] payload = {'ResetType': 'GracefulRestart'} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True} def manage_indicator_led(self, command): result = {} key = 'IndicatorLED' payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'} result = {} for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} if command in payloads.keys(): payload = {'IndicatorLED': payloads[command]} response = self.patch_request(self.root_uri + chassis_uri, payload) if response['ret'] is False: return response else: return {'ret': False, 'msg': 'Invalid command'} return result def _map_reset_type(self, reset_type, allowable_values): equiv_types = { 'On': 'ForceOn', 'ForceOn': 'On', 'ForceOff': 'GracefulShutdown', 'GracefulShutdown': 'ForceOff', 'GracefulRestart': 'ForceRestart', 'ForceRestart': 'GracefulRestart' } if reset_type in allowable_values: return reset_type if reset_type not in equiv_types: return reset_type mapped_type = equiv_types[reset_type] if mapped_type in allowable_values: return mapped_type return reset_type def manage_system_power(self, command): key = "Actions" reset_type_values = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] # command should be PowerOn, PowerForceOff, etc. if not command.startswith('Power'): return {'ret': False, 'msg': 'Invalid Command (%s)' % command} reset_type = command[5:] # map Reboot to a ResetType that does a reboot if reset_type == 'Reboot': reset_type = 'GracefulRestart' if reset_type not in reset_type_values: return {'ret': False, 'msg': 'Invalid Command (%s)' % command} # read the system resource and get the current power state response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response data = response['data'] power_state = data.get('PowerState') # if power is already in target state, nothing to do if power_state == "On" and reset_type in ['On', 'ForceOn']: return {'ret': True, 'changed': False} if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']: return {'ret': True, 'changed': False} # get the #ComputerSystem.Reset Action and target URI if key not in data or '#ComputerSystem.Reset' not in data[key]: return {'ret': False, 'msg': 'Action #ComputerSystem.Reset not found'} reset_action = data[key]['#ComputerSystem.Reset'] if 'target' not in reset_action: return {'ret': False, 'msg': 'target URI missing from Action #ComputerSystem.Reset'} action_uri = reset_action['target'] # get AllowableValues from ActionInfo allowable_values = None if '@Redfish.ActionInfo' in reset_action: action_info_uri = reset_action.get('@Redfish.ActionInfo') response = self.get_request(self.root_uri + action_info_uri) if response['ret'] is True: data = response['data'] if 'Parameters' in data: params = data['Parameters'] for param in params: if param.get('Name') == 'ResetType': allowable_values = param.get('AllowableValues') break # fallback to @Redfish.AllowableValues annotation if allowable_values is None: allowable_values = reset_action.get('[email protected]', []) # map ResetType to an allowable value if needed if reset_type not in allowable_values: reset_type = self._map_reset_type(reset_type, allowable_values) # define payload payload = {'ResetType': reset_type} # POST to Action URI response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def _find_account_uri(self, username=None, acct_id=None): if not any((username, acct_id)): return {'ret': False, 'msg': 'Must provide either account_id or account_username'} response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if username: if username == data.get('UserName'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} if acct_id: if acct_id == data.get('Id'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No account with the given account_id or account_username found'} def _find_empty_account_slot(self): response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] if uris: # first slot may be reserved, so move to end of list uris += [uris.pop(0)] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if data.get('UserName') == "" and not data.get('Enabled', True): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No empty account slot found'} def list_users(self): result = {} # listing all users has always been slower than other operations, why? user_list = [] users_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled'] response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for users in data.get('Members', []): user_list.append(users[u'@odata.id']) # user_list[] are URIs # for each user, get details for uri in user_list: user = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: user[property] = data[property] users_results.append(user) result["entries"] = users_results return result def add_user_via_patch(self, user): if user.get('account_id'): # If Id slot specified, use it response = self._find_account_uri(acct_id=user.get('account_id')) else: # Otherwise find first empty slot response = self._find_empty_account_slot() if not response['ret']: return response uri = response['uri'] payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def add_user(self, user): if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_account_uri(username=user.get('account_username')) if response['ret']: # account_username already exists, nothing to do return {'ret': True, 'changed': False} response = self.get_request(self.root_uri + self.accounts_uri) if not response['ret']: return response headers = response['headers'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'POST' not in methods: # if Allow header present and POST not listed, add via PATCH return self.add_user_via_patch(user) payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.post_request(self.root_uri + self.accounts_uri, payload) if not response['ret']: if response.get('status') == 405: # if POST returned a 405, try to add via PATCH return self.add_user_via_patch(user) else: return response return {'ret': True} def enable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('Enabled', True): # account already enabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': True} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user_via_patch(self, user, uri=None, data=None): if not uri: response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data and data.get('UserName') == '' and not data.get('Enabled', False): # account UserName already cleared, nothing to do return {'ret': True, 'changed': False} payload = {'UserName': ''} if 'Enabled' in data: payload['Enabled'] = False response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: if response.get('no_match'): # account does not exist, nothing to do return {'ret': True, 'changed': False} else: # some error encountered return response uri = response['uri'] headers = response['headers'] data = response['data'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'DELETE' not in methods: # if Allow header present and DELETE not listed, del via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) response = self.delete_request(self.root_uri + uri) if not response['ret']: if response.get('status') == 405: # if DELETE returned a 405, try to delete via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) else: return response return {'ret': True} def disable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if not data.get('Enabled'): # account already disabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': False} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_role(self, user): if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('RoleId') == user.get('account_roleid'): # account already has RoleId , nothing to do return {'ret': True, 'changed': False} payload = {'RoleId': user.get('account_roleid')} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_password(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'Password': user['account_password']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_name(self, user): if not user.get('account_updatename'): return {'ret': False, 'msg': 'Must provide account_updatename for UpdateUserName command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'UserName': user['account_updatename']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_accountservice_properties(self, user): if user.get('account_properties') is None: return {'ret': False, 'msg': 'Must provide account_properties for UpdateAccountServiceProperties command'} account_properties = user.get('account_properties') # Find AccountService response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} accountservice_uri = data["AccountService"]["@odata.id"] # Check support or not response = self.get_request(self.root_uri + accountservice_uri) if response['ret'] is False: return response data = response['data'] for property_name in account_properties.keys(): if property_name not in data: return {'ret': False, 'msg': 'property %s not supported' % property_name} # if properties is already matched, nothing to do need_change = False for property_name in account_properties.keys(): if account_properties[property_name] != data[property_name]: need_change = True break if not need_change: return {'ret': True, 'changed': False, 'msg': "AccountService properties already set"} payload = account_properties response = self.patch_request(self.root_uri + accountservice_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified AccountService properties"} def get_sessions(self): result = {} # listing all users has always been slower than other operations, why? session_list = [] sessions_results = [] # Get these entries, but does not fail if not found properties = ['Description', 'Id', 'Name', 'UserName'] response = self.get_request(self.root_uri + self.sessions_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for sessions in data[u'Members']: session_list.append(sessions[u'@odata.id']) # session_list[] are URIs # for each session, get details for uri in session_list: session = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: session[property] = data[property] sessions_results.append(session) result["entries"] = sessions_results return result def get_firmware_update_capabilities(self): result = {} response = self.get_request(self.root_uri + self.update_uri) if response['ret'] is False: return response result['ret'] = True result['entries'] = {} data = response['data'] if "Actions" in data: actions = data['Actions'] if len(actions) > 0: for key in actions.keys(): action = actions.get(key) if 'title' in action: title = action['title'] else: title = key result['entries'][title] = action.get('[email protected]', ["Key [email protected] not found"]) else: return {'ret': "False", 'msg': "Actions list is empty."} else: return {'ret': "False", 'msg': "Key Actions not found."} return result def _software_inventory(self, uri): result = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] result['entries'] = [] for member in data[u'Members']: uri = self.root_uri + member[u'@odata.id'] # Get details for each software or firmware member response = self.get_request(uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] software = {} # Get these standard properties if present for key in ['Name', 'Id', 'Status', 'Version', 'Updateable', 'SoftwareId', 'LowestSupportedVersion', 'Manufacturer', 'ReleaseDate']: if key in data: software[key] = data.get(key) result['entries'].append(software) return result def get_firmware_inventory(self): if self.firmware_uri is None: return {'ret': False, 'msg': 'No FirmwareInventory resource found'} else: return self._software_inventory(self.firmware_uri) def get_software_inventory(self): if self.software_uri is None: return {'ret': False, 'msg': 'No SoftwareInventory resource found'} else: return self._software_inventory(self.software_uri) def get_bios_attributes(self, systems_uri): result = {} bios_attributes = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for attribute in data[u'Attributes'].items(): bios_attributes[attribute[0]] = attribute[1] result["entries"] = bios_attributes return result def get_multi_bios_attributes(self): return self.aggregate(self.get_bios_attributes) def _get_boot_options_dict(self, boot): # Get these entries from BootOption, if present properties = ['DisplayName', 'BootOptionReference'] # Retrieve BootOptions if present if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']: boot_options_uri = boot['BootOptions']["@odata.id"] # Get BootOptions resource response = self.get_request(self.root_uri + boot_options_uri) if response['ret'] is False: return {} data = response['data'] # Retrieve Members array if 'Members' not in data: return {} members = data['Members'] else: members = [] # Build dict of BootOptions keyed by BootOptionReference boot_options_dict = {} for member in members: if '@odata.id' not in member: return {} boot_option_uri = member['@odata.id'] response = self.get_request(self.root_uri + boot_option_uri) if response['ret'] is False: return {} data = response['data'] if 'BootOptionReference' not in data: return {} boot_option_ref = data['BootOptionReference'] # fetch the props to display for this boot device boot_props = {} for prop in properties: if prop in data: boot_props[prop] = data[prop] boot_options_dict[boot_option_ref] = boot_props return boot_options_dict def get_boot_order(self, systems_uri): result = {} # Retrieve System resource response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # Build boot device list boot_device_list = [] for ref in boot_order: boot_device_list.append( boot_options_dict.get(ref, {'BootOptionReference': ref})) result["entries"] = boot_device_list return result def get_multi_boot_order(self): return self.aggregate(self.get_boot_order) def get_boot_override(self, systems_uri): result = {} properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget", "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "[email protected]"] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Boot' not in data: return {'ret': False, 'msg': "Key Boot not found"} boot = data['Boot'] boot_overrides = {} if "BootSourceOverrideEnabled" in boot: if boot["BootSourceOverrideEnabled"] is not False: for property in properties: if property in boot: if boot[property] is not None: boot_overrides[property] = boot[property] else: return {'ret': False, 'msg': "No boot override is enabled."} result['entries'] = boot_overrides return result def get_multi_boot_override(self): return self.aggregate(self.get_boot_override) def set_bios_default_settings(self): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] reset_bios_settings_uri = data["Actions"]["#Bios.ResetBios"]["target"] response = self.post_request(self.root_uri + reset_bios_settings_uri, {}) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Set BIOS to default settings"} def set_one_time_boot_device(self, bootdevice, uefi_target, boot_next): result = {} key = "Boot" if not bootdevice: return {'ret': False, 'msg': "bootdevice option required for SetOneTimeBoot"} # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} boot = data[key] annotation = '[email protected]' if annotation in boot: allowable_values = boot[annotation] if isinstance(allowable_values, list) and bootdevice not in allowable_values: return {'ret': False, 'msg': "Boot device %s not in list of allowable values (%s)" % (bootdevice, allowable_values)} # read existing values enabled = boot.get('BootSourceOverrideEnabled') target = boot.get('BootSourceOverrideTarget') cur_uefi_target = boot.get('UefiTargetBootSourceOverride') cur_boot_next = boot.get('BootNext') if bootdevice == 'UefiTarget': if not uefi_target: return {'ret': False, 'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"} if enabled == 'Once' and target == bootdevice and uefi_target == cur_uefi_target: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'UefiTargetBootSourceOverride': uefi_target } } elif bootdevice == 'UefiBootNext': if not boot_next: return {'ret': False, 'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"} if enabled == 'Once' and target == bootdevice and boot_next == cur_boot_next: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'BootNext': boot_next } } else: if enabled == 'Once' and target == bootdevice: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice } } response = self.patch_request(self.root_uri + self.systems_uris[0], payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def set_bios_attributes(self, attr): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # First, check if BIOS attribute exists if attr['bios_attr_name'] not in data[u'Attributes']: return {'ret': False, 'msg': "BIOS attribute not found"} # Find out if value is already set to what we want. If yes, return if data[u'Attributes'][attr['bios_attr_name']] == attr['bios_attr_value']: return {'ret': True, 'changed': False, 'msg': "BIOS attribute already set"} set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"]["@odata.id"] # Example: bios_attr = {\"name\":\"value\"} bios_attr = "{\"" + attr['bios_attr_name'] + "\":\"" + attr['bios_attr_value'] + "\"}" payload = {"Attributes": json.loads(bios_attr)} response = self.patch_request(self.root_uri + set_bios_attr_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified BIOS attribute"} def set_boot_order(self, boot_list): if not boot_list: return {'ret': False, 'msg': "boot_order list required for SetBootOrder command"} # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # validate boot_list against BootOptionReferences if available if boot_options_dict: boot_option_references = boot_options_dict.keys() for ref in boot_list: if ref not in boot_option_references: return {'ret': False, 'msg': "BootOptionReference %s not found in BootOptions" % ref} # If requested BootOrder is already set, nothing to do if boot_order == boot_list: return {'ret': True, 'changed': False, 'msg': "BootOrder already set to %s" % boot_list} payload = { 'Boot': { 'BootOrder': boot_list } } response = self.patch_request(self.root_uri + systems_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set"} def set_default_boot_order(self): # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # get the #ComputerSystem.SetDefaultBootOrder Action and target URI action = '#ComputerSystem.SetDefaultBootOrder' if 'Actions' not in data or action not in data['Actions']: return {'ret': False, 'msg': 'Action %s not found' % action} if 'target' not in data['Actions'][action]: return {'ret': False, 'msg': 'target URI missing from Action %s' % action} action_uri = data['Actions'][action]['target'] # POST to Action URI payload = {} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set to default"} def get_chassis_inventory(self): result = {} chassis_results = [] # Get these entries, but does not fail if not found properties = ['ChassisType', 'PartNumber', 'AssetTag', 'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] chassis_result = {} for property in properties: if property in data: chassis_result[property] = data[property] chassis_results.append(chassis_result) result["entries"] = chassis_results return result def get_fan_inventory(self): result = {} fan_results = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['FanName', 'Reading', 'ReadingUnits', 'Status'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: # match: found an entry for "Thermal" information = fans thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for device in data[u'Fans']: fan = {} for property in properties: if property in device: fan[property] = device[property] fan_results.append(fan) result["entries"] = fan_results return result def get_chassis_power(self): result = {} key = "Power" # Get these entries, but does not fail if not found properties = ['Name', 'PowerAllocatedWatts', 'PowerAvailableWatts', 'PowerCapacityWatts', 'PowerConsumedWatts', 'PowerMetrics', 'PowerRequestedWatts', 'RelatedItem', 'Status'] chassis_power_results = [] # Go through list for chassis_uri in self.chassis_uri_list: chassis_power_result = {} response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: response = self.get_request(self.root_uri + data[key]['@odata.id']) data = response['data'] if 'PowerControl' in data: if len(data['PowerControl']) > 0: data = data['PowerControl'][0] for property in properties: if property in data: chassis_power_result[property] = data[property] else: return {'ret': False, 'msg': 'Key PowerControl not found.'} chassis_power_results.append(chassis_power_result) else: return {'ret': False, 'msg': 'Key Power not found.'} result['entries'] = chassis_power_results return result def get_chassis_thermals(self): result = {} sensors = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical', 'UpperThresholdFatal', 'UpperThresholdNonCritical', 'LowerThresholdCritical', 'LowerThresholdFatal', 'LowerThresholdNonCritical', 'MaxReadingRangeTemp', 'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem', 'SensorNumber'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if "Temperatures" in data: for sensor in data[u'Temperatures']: sensor_result = {} for property in properties: if property in sensor: if sensor[property] is not None: sensor_result[property] = sensor[property] sensors.append(sensor_result) if sensors is None: return {'ret': False, 'msg': 'Key Temperatures was not found.'} result['entries'] = sensors return result def get_cpu_inventory(self, systems_uri): result = {} cpu_list = [] cpu_results = [] key = "Processors" # Get these entries, but does not fail if not found properties = ['Id', 'Manufacturer', 'Model', 'MaxSpeedMHz', 'TotalCores', 'TotalThreads', 'Status'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} processors_uri = data[key]["@odata.id"] # Get a list of all CPUs and build respective URIs response = self.get_request(self.root_uri + processors_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for cpu in data[u'Members']: cpu_list.append(cpu[u'@odata.id']) for c in cpu_list: cpu = {} uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: cpu[property] = data[property] cpu_results.append(cpu) result["entries"] = cpu_results return result def get_multi_cpu_inventory(self): return self.aggregate(self.get_cpu_inventory) def get_memory_inventory(self, systems_uri): result = {} memory_list = [] memory_results = [] key = "Memory" # Get these entries, but does not fail if not found properties = ['SerialNumber', 'MemoryDeviceType', 'PartNuber', 'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} memory_uri = data[key]["@odata.id"] # Get a list of all DIMMs and build respective URIs response = self.get_request(self.root_uri + memory_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for dimm in data[u'Members']: memory_list.append(dimm[u'@odata.id']) for m in memory_list: dimm = {} uri = self.root_uri + m response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if "Status" in data: if "State" in data["Status"]: if data["Status"]["State"] == "Absent": continue else: continue for property in properties: if property in data: dimm[property] = data[property] memory_results.append(dimm) result["entries"] = memory_results return result def get_multi_memory_inventory(self): return self.aggregate(self.get_memory_inventory) def get_nic_inventory(self, resource_uri): result = {} nic_list = [] nic_results = [] key = "EthernetInterfaces" # Get these entries, but does not fail if not found properties = ['Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses', 'NameServers', 'MACAddress', 'PermanentMACAddress', 'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} ethernetinterfaces_uri = data[key]["@odata.id"] # Get a list of all network controllers and build respective URIs response = self.get_request(self.root_uri + ethernetinterfaces_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for nic in data[u'Members']: nic_list.append(nic[u'@odata.id']) for n in nic_list: nic = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: nic[property] = data[property] nic_results.append(nic) result["entries"] = nic_results return result def get_multi_nic_inventory(self, resource_type): ret = True entries = [] # Given resource_type, use the proper URI if resource_type == 'Systems': resource_uris = self.systems_uris elif resource_type == 'Manager': # put in a list to match what we're doing with systems_uris resource_uris = [self.manager_uri] for resource_uri in resource_uris: inventory = self.get_nic_inventory(resource_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'resource_uri': resource_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_virtualmedia(self, resource_uri): result = {} virtualmedia_list = [] virtualmedia_results = [] key = "VirtualMedia" # Get these entries, but does not fail if not found properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes', 'Image', 'ImageName', 'Name', 'WriteProtected', 'TransferMethod', 'TransferProtocolType'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} virtualmedia_uri = data[key]["@odata.id"] # Get a list of all virtual media and build respective URIs response = self.get_request(self.root_uri + virtualmedia_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for virtualmedia in data[u'Members']: virtualmedia_list.append(virtualmedia[u'@odata.id']) for n in virtualmedia_list: virtualmedia = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: virtualmedia[property] = data[property] virtualmedia_results.append(virtualmedia) result["entries"] = virtualmedia_results return result def get_multi_virtualmedia(self): ret = True entries = [] # Because _find_managers_resource() only find last Manager uri in self.manager_uri, not one list. This should be 1 issue. # I have to put manager_uri into list to reduce future changes when the issue is fixed. resource_uris = [self.manager_uri] for resource_uri in resource_uris: virtualmedia = self.get_virtualmedia(resource_uri) ret = virtualmedia.pop('ret') and ret if 'entries' in virtualmedia: entries.append(({'resource_uri': resource_uri}, virtualmedia['entries'])) return dict(ret=ret, entries=entries) def get_psu_inventory(self): result = {} psu_list = [] psu_results = [] key = "PowerSupplies" # Get these entries, but does not fail if not found properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status'] # Get a list of all Chassis and build URIs, then get all PowerSupplies # from each Power entry in the Chassis chassis_uri_list = self.chassis_uri_list for chassis_uri in chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Power' in data: power_uri = data[u'Power'][u'@odata.id'] else: continue response = self.get_request(self.root_uri + power_uri) data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} psu_list = data[key] for psu in psu_list: psu_not_present = False psu_data = {} for property in properties: if property in psu: if psu[property] is not None: if property == 'Status': if 'State' in psu[property]: if psu[property]['State'] == 'Absent': psu_not_present = True psu_data[property] = psu[property] if psu_not_present: continue psu_results.append(psu_data) result["entries"] = psu_results if not result["entries"]: return {'ret': False, 'msg': "No PowerSupply objects found"} return result def get_multi_psu_inventory(self): return self.aggregate(self.get_psu_inventory) def get_system_inventory(self, systems_uri): result = {} inventory = {} # Get these entries, but does not fail if not found properties = ['Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag', 'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary', 'ProcessorSummary', 'TrustedModules'] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for property in properties: if property in data: inventory[property] = data[property] result["entries"] = inventory return result def get_multi_system_inventory(self): return self.aggregate(self.get_system_inventory)
closed
ansible/ansible
https://github.com/ansible/ansible
62,819
redfish_info / redfish_config - Manager - GetManagerServices / SetManagerServices
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> This feature would implement a GetManagerServices command for the Manager category of redfish_info, to retrieve a list of NetworkProtocol and their properties, like SSH, Port, Enable or Disable. And also implement a SetManagerServices command for the Manager category of redfish_config, to set NetworkProtocol's properties, like enable/disable SSH, change Port. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_config ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> These 2 commands would help user to get the status of services or control the status of services Manager provided. <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/62819
https://github.com/ansible/ansible/pull/62815
4e8bb334a9da287bb31775db2e7f4e7318ec90ca
8316fa66e8a16fb15e16d18fdff001f6617d9ef4
2019-09-25T07:16:11Z
python
2019-10-31T07:57:20Z
lib/ansible/modules/remote_management/redfish/redfish_config.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_config version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to set or update a configuration attribute. - Manages BIOS configuration settings. - Manages OOB controller configuration settings. options: category: required: true description: - Category to execute on OOB controller type: str command: required: true description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - User for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str bios_attribute_name: required: false description: - name of BIOS attribute to update default: 'null' type: str version_added: "2.8" bios_attribute_value: required: false description: - value of BIOS attribute to update default: 'null' type: str version_added: "2.8" timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: "2.8" boot_order: required: false description: - list of BootOptionReference strings specifying the BootOrder default: [] type: list version_added: "2.10" author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Set BootMode to UEFI redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: BootMode bios_attribute_value: Uefi baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set BootMode to Legacy BIOS redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: BootMode bios_attribute_value: Bios baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Enable PXE Boot for NIC1 redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: PxeDev1EnDis bios_attribute_value: Enabled baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set BIOS default settings with a timeout of 20 seconds redfish_config: category: Systems command: SetBiosDefaultSettings baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 - name: Set boot order redfish_config: category: Systems command: SetBootOrder boot_order: - Boot0002 - Boot0001 - Boot0000 - Boot0003 - Boot0004 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set boot order to the default redfish_config: category: Systems command: SetDefaultBootOrder baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native # More will be added as module features are expanded CATEGORY_COMMANDS_ALL = { "Systems": ["SetBiosDefaultSettings", "SetBiosAttributes", "SetBootOrder", "SetDefaultBootOrder"] } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), bios_attribute_name=dict(default='null'), bios_attribute_value=dict(default='null'), timeout=dict(type='int', default=10), boot_order=dict(type='list', elements='str', default=[]) ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # BIOS attributes to update bios_attributes = {'bios_attr_name': module.params['bios_attribute_name'], 'bios_attr_value': module.params['bios_attribute_value']} # boot order boot_order = module.params['boot_order'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetBiosDefaultSettings": result = rf_utils.set_bios_default_settings() elif command == "SetBiosAttributes": result = rf_utils.set_bios_attributes(bios_attributes) elif command == "SetBootOrder": result = rf_utils.set_boot_order(boot_order) elif command == "SetDefaultBootOrder": result = rf_utils.set_default_boot_order() # Return data back or fail with proper message if result['ret'] is True: module.exit_json(changed=result['changed'], msg=to_native(result['msg'])) else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
62,819
redfish_info / redfish_config - Manager - GetManagerServices / SetManagerServices
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> This feature would implement a GetManagerServices command for the Manager category of redfish_info, to retrieve a list of NetworkProtocol and their properties, like SSH, Port, Enable or Disable. And also implement a SetManagerServices command for the Manager category of redfish_config, to set NetworkProtocol's properties, like enable/disable SSH, change Port. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_config ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> These 2 commands would help user to get the status of services or control the status of services Manager provided. <!--- Paste example playbooks or commands between quotes below --> ```yaml ``` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/62819
https://github.com/ansible/ansible/pull/62815
4e8bb334a9da287bb31775db2e7f4e7318ec90ca
8316fa66e8a16fb15e16d18fdff001f6617d9ef4
2019-09-25T07:16:11Z
python
2019-10-31T07:57:20Z
lib/ansible/modules/remote_management/redfish/redfish_info.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_info version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to get information back. - Information retrieved is placed in a location specified by the user. - This module was called C(redfish_facts) before Ansible 2.9, returning C(ansible_facts). Note that the M(redfish_info) module no longer returns C(ansible_facts)! options: category: required: false description: - List of categories to execute on OOB controller default: ['Systems'] type: list command: required: false description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - User for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: '2.8' author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Get CPU inventory redfish_info: category: Systems command: GetCpuInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.cpu.entries | to_nice_json }}" - name: Get CPU model redfish_info: category: Systems command: GetCpuInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.cpu.entries.0.Model }}" - name: Get memory inventory redfish_info: category: Systems command: GetMemoryInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - name: Get fan inventory with a timeout of 20 seconds redfish_info: category: Chassis command: GetFanInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 register: result - name: Get Virtual Media information redfish_info: category: Manager command: GetVirtualMedia baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.virtual_media.entries | to_nice_json }}" - name: Get Volume Inventory redfish_info: category: Systems command: GetVolumeInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.volume.entries | to_nice_json }}" - name: Get Session information redfish_info: category: Sessions command: GetSessions baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts.session.entries | to_nice_json }}" - name: Get default inventory information redfish_info: baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" register: result - debug: msg: "{{ result.redfish_facts | to_nice_json }}" - name: Get several inventories redfish_info: category: Systems command: GetNicInventory,GetBiosAttributes baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get default system inventory and user information redfish_info: category: Systems,Accounts baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get default system, user and firmware information redfish_info: category: ["Systems", "Accounts", "Update"] baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get Manager NIC inventory information redfish_info: category: Manager command: GetManagerNicInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get boot override information redfish_info: category: Systems command: GetBootOverride baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get chassis inventory redfish_info: category: Chassis command: GetChassisInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get all information available in the Manager category redfish_info: category: Manager command: all baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get firmware update capability information redfish_info: category: Update command: GetFirmwareUpdateCapabilities baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get firmware inventory redfish_info: category: Update command: GetFirmwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get software inventory redfish_info: category: Update command: GetSoftwareInventory baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Get all information available in all categories redfish_info: category: all command: all baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ''' RETURN = ''' result: description: different results depending on task returned: always type: dict sample: List of CPUs on system ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils CATEGORY_COMMANDS_ALL = { "Systems": ["GetSystemInventory", "GetPsuInventory", "GetCpuInventory", "GetMemoryInventory", "GetNicInventory", "GetStorageControllerInventory", "GetDiskInventory", "GetVolumeInventory", "GetBiosAttributes", "GetBootOrder", "GetBootOverride"], "Chassis": ["GetFanInventory", "GetPsuInventory", "GetChassisPower", "GetChassisThermals", "GetChassisInventory"], "Accounts": ["ListUsers"], "Sessions": ["GetSessions"], "Update": ["GetFirmwareInventory", "GetFirmwareUpdateCapabilities", "GetSoftwareInventory"], "Manager": ["GetManagerNicInventory", "GetVirtualMedia", "GetLogs"], } CATEGORY_COMMANDS_DEFAULT = { "Systems": "GetSystemInventory", "Chassis": "GetFanInventory", "Accounts": "ListUsers", "Update": "GetFirmwareInventory", "Sessions": "GetSessions", "Manager": "GetManagerNicInventory" } def main(): result = {} category_list = [] module = AnsibleModule( argument_spec=dict( category=dict(type='list', default=['Systems']), command=dict(type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), timeout=dict(type='int', default=10) ), supports_check_mode=False ) is_old_facts = module._name == 'redfish_facts' if is_old_facts: module.deprecate("The 'redfish_facts' module has been renamed to 'redfish_info', " "and the renamed one no longer returns ansible_facts", version='2.13') # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Build Category list if "all" in module.params['category']: for entry in CATEGORY_COMMANDS_ALL: category_list.append(entry) else: # one or more categories specified category_list = module.params['category'] for category in category_list: command_list = [] # Build Command list for each Category if category in CATEGORY_COMMANDS_ALL: if not module.params['command']: # True if we don't specify a command --> use default command_list.append(CATEGORY_COMMANDS_DEFAULT[category]) elif "all" in module.params['command']: for entry in range(len(CATEGORY_COMMANDS_ALL[category])): command_list.append(CATEGORY_COMMANDS_ALL[category][entry]) # one or more commands else: command_list = module.params['command'] # Verify that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg="Invalid Command: %s" % cmd) else: # Fail if even one category given is invalid module.fail_json(msg="Invalid Category: %s" % category) # Organize by Categories / Commands if category == "Systems": # execute only if we find a Systems resource resource = rf_utils._find_systems_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetSystemInventory": result["system"] = rf_utils.get_multi_system_inventory() elif command == "GetCpuInventory": result["cpu"] = rf_utils.get_multi_cpu_inventory() elif command == "GetMemoryInventory": result["memory"] = rf_utils.get_multi_memory_inventory() elif command == "GetNicInventory": result["nic"] = rf_utils.get_multi_nic_inventory(category) elif command == "GetStorageControllerInventory": result["storage_controller"] = rf_utils.get_multi_storage_controller_inventory() elif command == "GetDiskInventory": result["disk"] = rf_utils.get_multi_disk_inventory() elif command == "GetVolumeInventory": result["volume"] = rf_utils.get_multi_volume_inventory() elif command == "GetBiosAttributes": result["bios_attribute"] = rf_utils.get_multi_bios_attributes() elif command == "GetBootOrder": result["boot_order"] = rf_utils.get_multi_boot_order() elif command == "GetBootOverride": result["boot_override"] = rf_utils.get_multi_boot_override() elif category == "Chassis": # execute only if we find Chassis resource resource = rf_utils._find_chassis_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetFanInventory": result["fan"] = rf_utils.get_fan_inventory() elif command == "GetPsuInventory": result["psu"] = rf_utils.get_psu_inventory() elif command == "GetChassisThermals": result["thermals"] = rf_utils.get_chassis_thermals() elif command == "GetChassisPower": result["chassis_power"] = rf_utils.get_chassis_power() elif command == "GetChassisInventory": result["chassis"] = rf_utils.get_chassis_inventory() elif category == "Accounts": # execute only if we find an Account service resource resource = rf_utils._find_accountservice_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "ListUsers": result["user"] = rf_utils.list_users() elif category == "Update": # execute only if we find UpdateService resources resource = rf_utils._find_updateservice_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetFirmwareInventory": result["firmware"] = rf_utils.get_firmware_inventory() elif command == "GetSoftwareInventory": result["software"] = rf_utils.get_software_inventory() elif command == "GetFirmwareUpdateCapabilities": result["firmware_update_capabilities"] = rf_utils.get_firmware_update_capabilities() elif category == "Sessions": # execute only if we find SessionService resources resource = rf_utils._find_sessionservice_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetSessions": result["session"] = rf_utils.get_sessions() elif category == "Manager": # execute only if we find a Manager service resource resource = rf_utils._find_managers_resource() if resource['ret'] is False: module.fail_json(msg=resource['msg']) for command in command_list: if command == "GetManagerNicInventory": result["manager_nics"] = rf_utils.get_multi_nic_inventory(category) elif command == "GetVirtualMedia": result["virtual_media"] = rf_utils.get_multi_virtualmedia() elif command == "GetLogs": result["log"] = rf_utils.get_logs() # Return data back if is_old_facts: module.exit_json(ansible_facts=dict(redfish_facts=result)) else: module.exit_json(redfish_facts=result) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
62,810
vmware_guest and server names with dashes issue
I am trying to use the vmware_guest module to deploy a Windows 2016 VM from template in a VMware 6.0 and 6.5 vCenter environment while using a server name with a dash in the name (eg, SERVER-NAME). The display name of the VM is created correctly in vCenter but after guest customization, the server name in the Windows OS appears without the dash (eg, SERVERNAME). Is there an option I am missing to use the correct name or is this a bug? Deploying the template using vCenter with this name works correctly. Thanks! Ansible host: CentOS 7.3.1611 ansible 2.8.1 pyvmomi 6.7.3 vCenters 6.0 and 6.5
https://github.com/ansible/ansible/issues/62810
https://github.com/ansible/ansible/pull/64052
8316fa66e8a16fb15e16d18fdff001f6617d9ef4
548fa65ac6db1f3b24944a106fa01872362fea17
2019-09-24T20:30:36Z
python
2019-10-31T08:32:52Z
changelogs/fragments/62810-Vmware-Guest-Allow-DashInWindowsServerDNSName.yml
closed
ansible/ansible
https://github.com/ansible/ansible
62,810
vmware_guest and server names with dashes issue
I am trying to use the vmware_guest module to deploy a Windows 2016 VM from template in a VMware 6.0 and 6.5 vCenter environment while using a server name with a dash in the name (eg, SERVER-NAME). The display name of the VM is created correctly in vCenter but after guest customization, the server name in the Windows OS appears without the dash (eg, SERVERNAME). Is there an option I am missing to use the correct name or is this a bug? Deploying the template using vCenter with this name works correctly. Thanks! Ansible host: CentOS 7.3.1611 ansible 2.8.1 pyvmomi 6.7.3 vCenters 6.0 and 6.5
https://github.com/ansible/ansible/issues/62810
https://github.com/ansible/ansible/pull/64052
8316fa66e8a16fb15e16d18fdff001f6617d9ef4
548fa65ac6db1f3b24944a106fa01872362fea17
2019-09-24T20:30:36Z
python
2019-10-31T08:32:52Z
lib/ansible/modules/cloud/vmware/vmware_guest.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # This module is also sponsored by E.T.A.I. (www.etai.fr) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: vmware_guest short_description: Manages virtual machines in vCenter description: > This module can be used to create new virtual machines from templates or other virtual machines, manage power state of virtual machine such as power on, power off, suspend, shutdown, reboot, restart etc., modify various virtual machine components like network, disk, customization etc., rename a virtual machine and remove a virtual machine with associated components. version_added: '2.2' author: - Loic Blot (@nerzhul) <[email protected]> - Philippe Dellaert (@pdellaert) <[email protected]> - Abhijeet Kasurde (@Akasurde) <[email protected]> requirements: - python >= 2.6 - PyVmomi notes: - Please make sure that the user used for vmware_guest has the correct level of privileges. - For example, following is the list of minimum privileges required by users to create virtual machines. - " DataStore > Allocate Space" - " Virtual Machine > Configuration > Add New Disk" - " Virtual Machine > Configuration > Add or Remove Device" - " Virtual Machine > Inventory > Create New" - " Network > Assign Network" - " Resource > Assign Virtual Machine to Resource Pool" - "Module may require additional privileges as well, which may be required for gathering facts - e.g. ESXi configurations." - Tested on vSphere 5.5, 6.0, 6.5 and 6.7 - Use SCSI disks instead of IDE when you want to expand online disks by specifying a SCSI controller - "For additional information please visit Ansible VMware community wiki - U(https://github.com/ansible/community/wiki/VMware)." options: state: description: - Specify the state the virtual machine should be in. - 'If C(state) is set to C(present) and virtual machine exists, ensure the virtual machine configurations conforms to task arguments.' - 'If C(state) is set to C(absent) and virtual machine exists, then the specified virtual machine is removed with its associated components.' - 'If C(state) is set to one of the following C(poweredon), C(poweredoff), C(present), C(restarted), C(suspended) and virtual machine does not exists, then virtual machine is deployed with given parameters.' - 'If C(state) is set to C(poweredon) and virtual machine exists with powerstate other than powered on, then the specified virtual machine is powered on.' - 'If C(state) is set to C(poweredoff) and virtual machine exists with powerstate other than powered off, then the specified virtual machine is powered off.' - 'If C(state) is set to C(restarted) and virtual machine exists, then the virtual machine is restarted.' - 'If C(state) is set to C(suspended) and virtual machine exists, then the virtual machine is set to suspended mode.' - 'If C(state) is set to C(shutdownguest) and virtual machine exists, then the virtual machine is shutdown.' - 'If C(state) is set to C(rebootguest) and virtual machine exists, then the virtual machine is rebooted.' default: present choices: [ present, absent, poweredon, poweredoff, restarted, suspended, shutdownguest, rebootguest ] name: description: - Name of the virtual machine to work with. - Virtual machine names in vCenter are not necessarily unique, which may be problematic, see C(name_match). - 'If multiple virtual machines with same name exists, then C(folder) is required parameter to identify uniqueness of the virtual machine.' - This parameter is required, if C(state) is set to C(poweredon), C(poweredoff), C(present), C(restarted), C(suspended) and virtual machine does not exists. - This parameter is case sensitive. required: yes name_match: description: - If multiple virtual machines matching the name, use the first or last found. default: 'first' choices: [ first, last ] uuid: description: - UUID of the virtual machine to manage if known, this is VMware's unique identifier. - This is required if C(name) is not supplied. - If virtual machine does not exists, then this parameter is ignored. - Please note that a supplied UUID will be ignored on virtual machine creation, as VMware creates the UUID internally. use_instance_uuid: description: - Whether to use the VMware instance UUID rather than the BIOS UUID. default: no type: bool version_added: '2.8' template: description: - Template or existing virtual machine used to create new virtual machine. - If this value is not set, virtual machine is created without using a template. - If the virtual machine already exists, this parameter will be ignored. - This parameter is case sensitive. - You can also specify template or VM UUID for identifying source. version_added 2.8. Use C(hw_product_uuid) from M(vmware_guest_facts) as UUID value. - From version 2.8 onwards, absolute path to virtual machine or template can be used. aliases: [ 'template_src' ] is_template: description: - Flag the instance as a template. - This will mark the given virtual machine as template. default: 'no' type: bool version_added: '2.3' folder: description: - Destination folder, absolute path to find an existing guest or create the new guest. - The folder should include the datacenter. ESX's datacenter is ha-datacenter. - This parameter is case sensitive. - This parameter is required, while deploying new virtual machine. version_added 2.5. - 'If multiple machines are found with same name, this parameter is used to identify uniqueness of the virtual machine. version_added 2.5' - 'Examples:' - ' folder: /ha-datacenter/vm' - ' folder: ha-datacenter/vm' - ' folder: /datacenter1/vm' - ' folder: datacenter1/vm' - ' folder: /datacenter1/vm/folder1' - ' folder: datacenter1/vm/folder1' - ' folder: /folder1/datacenter1/vm' - ' folder: folder1/datacenter1/vm' - ' folder: /folder1/datacenter1/vm/folder2' hardware: description: - Manage virtual machine's hardware attributes. - All parameters case sensitive. - 'Valid attributes are:' - ' - C(hotadd_cpu) (boolean): Allow virtual CPUs to be added while the virtual machine is running.' - ' - C(hotremove_cpu) (boolean): Allow virtual CPUs to be removed while the virtual machine is running. version_added: 2.5' - ' - C(hotadd_memory) (boolean): Allow memory to be added while the virtual machine is running.' - ' - C(memory_mb) (integer): Amount of memory in MB.' - ' - C(nested_virt) (bool): Enable nested virtualization. version_added: 2.5' - ' - C(num_cpus) (integer): Number of CPUs.' - ' - C(num_cpu_cores_per_socket) (integer): Number of Cores Per Socket.' - " C(num_cpus) must be a multiple of C(num_cpu_cores_per_socket). For example to create a VM with 2 sockets of 4 cores, specify C(num_cpus): 8 and C(num_cpu_cores_per_socket): 4" - ' - C(scsi) (string): Valid values are C(buslogic), C(lsilogic), C(lsilogicsas) and C(paravirtual) (default).' - " - C(memory_reservation_lock) (boolean): If set true, memory resource reservation for the virtual machine will always be equal to the virtual machine's memory size. version_added: 2.5" - ' - C(max_connections) (integer): Maximum number of active remote display connections for the virtual machines. version_added: 2.5.' - ' - C(mem_limit) (integer): The memory utilization of a virtual machine will not exceed this limit. Unit is MB. version_added: 2.5' - ' - C(mem_reservation) (integer): The amount of memory resource that is guaranteed available to the virtual machine. Unit is MB. C(memory_reservation) is alias to this. version_added: 2.5' - ' - C(cpu_limit) (integer): The CPU utilization of a virtual machine will not exceed this limit. Unit is MHz. version_added: 2.5' - ' - C(cpu_reservation) (integer): The amount of CPU resource that is guaranteed available to the virtual machine. Unit is MHz. version_added: 2.5' - ' - C(version) (integer): The Virtual machine hardware versions. Default is 10 (ESXi 5.5 and onwards). If value specified as C(latest), version is set to the most current virtual hardware supported on the host. C(latest) is added in version 2.10. Please check VMware documentation for correct virtual machine hardware version. Incorrect hardware version may lead to failure in deployment. If hardware version is already equal to the given version then no action is taken. version_added: 2.6' - ' - C(boot_firmware) (string): Choose which firmware should be used to boot the virtual machine. Allowed values are "bios" and "efi". version_added: 2.7' - ' - C(virt_based_security) (bool): Enable Virtualization Based Security feature for Windows 10. (Support from Virtual machine hardware version 14, Guest OS Windows 10 64 bit, Windows Server 2016)' guest_id: description: - Set the guest ID. - This parameter is case sensitive. - 'Examples:' - " virtual machine with RHEL7 64 bit, will be 'rhel7_64Guest'" - " virtual machine with CentOS 64 bit, will be 'centos64Guest'" - " virtual machine with Ubuntu 64 bit, will be 'ubuntu64Guest'" - This field is required when creating a virtual machine, not required when creating from the template. - > Valid values are referenced here: U(https://code.vmware.com/apis/358/doc/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html) version_added: '2.3' disk: description: - A list of disks to add. - This parameter is case sensitive. - Shrinking disks is not supported. - Removing existing disks of the virtual machine is not supported. - 'Valid attributes are:' - ' - C(size_[tb,gb,mb,kb]) (integer): Disk storage size in specified unit.' - ' - C(type) (string): Valid values are:' - ' - C(thin) thin disk' - ' - C(eagerzeroedthick) eagerzeroedthick disk, added in version 2.5' - ' Default: C(None) thick disk, no eagerzero.' - ' - C(datastore) (string): The name of datastore which will be used for the disk. If C(autoselect_datastore) is set to True, then will select the less used datastore whose name contains this "disk.datastore" string.' - ' - C(filename) (string): Existing disk image to be used. Filename must already exist on the datastore.' - ' Specify filename string in C([datastore_name] path/to/file.vmdk) format. Added in version 2.8.' - ' - C(autoselect_datastore) (bool): select the less used datastore. "disk.datastore" and "disk.autoselect_datastore" will not be used if C(datastore) is specified outside this C(disk) configuration.' - ' - C(disk_mode) (string): Type of disk mode. Added in version 2.6' - ' - Available options are :' - ' - C(persistent): Changes are immediately and permanently written to the virtual disk. This is default.' - ' - C(independent_persistent): Same as persistent, but not affected by snapshots.' - ' - C(independent_nonpersistent): Changes to virtual disk are made to a redo log and discarded at power off, but not affected by snapshots.' cdrom: description: - A CD-ROM configuration for the virtual machine. - Or a list of CD-ROMs configuration for the virtual machine. Added in version 2.9. - 'Parameters C(controller_type), C(controller_number), C(unit_number), C(state) are added for a list of CD-ROMs configuration support.' - 'Valid attributes are:' - ' - C(type) (string): The type of CD-ROM, valid options are C(none), C(client) or C(iso). With C(none) the CD-ROM will be disconnected but present.' - ' - C(iso_path) (string): The datastore path to the ISO file to use, in the form of C([datastore1] path/to/file.iso). Required if type is set C(iso).' - ' - C(controller_type) (string): Default value is C(ide). Only C(ide) controller type for CD-ROM is supported for now, will add SATA controller type in the future.' - ' - C(controller_number) (int): For C(ide) controller, valid value is 0 or 1.' - ' - C(unit_number) (int): For CD-ROM device attach to C(ide) controller, valid value is 0 or 1. C(controller_number) and C(unit_number) are mandatory attributes.' - ' - C(state) (string): Valid value is C(present) or C(absent). Default is C(present). If set to C(absent), then the specified CD-ROM will be removed. For C(ide) controller, hot-add or hot-remove CD-ROM is not supported.' version_added: '2.5' resource_pool: description: - Use the given resource pool for virtual machine operation. - This parameter is case sensitive. - Resource pool should be child of the selected host parent. version_added: '2.3' wait_for_ip_address: description: - Wait until vCenter detects an IP address for the virtual machine. - This requires vmware-tools (vmtoolsd) to properly work after creation. - "vmware-tools needs to be installed on the given virtual machine in order to work with this parameter." default: 'no' type: bool wait_for_ip_address_timeout: description: - Define a timeout (in seconds) for the wait_for_ip_address parameter. default: '300' type: int version_added: '2.10' wait_for_customization: description: - Wait until vCenter detects all guest customizations as successfully completed. - When enabled, the VM will automatically be powered on. default: 'no' type: bool version_added: '2.8' state_change_timeout: description: - If the C(state) is set to C(shutdownguest), by default the module will return immediately after sending the shutdown signal. - If this argument is set to a positive integer, the module will instead wait for the virtual machine to reach the poweredoff state. - The value sets a timeout in seconds for the module to wait for the state change. default: 0 version_added: '2.6' snapshot_src: description: - Name of the existing snapshot to use to create a clone of a virtual machine. - This parameter is case sensitive. - While creating linked clone using C(linked_clone) parameter, this parameter is required. version_added: '2.4' linked_clone: description: - Whether to create a linked clone from the snapshot specified. - If specified, then C(snapshot_src) is required parameter. default: 'no' type: bool version_added: '2.4' force: description: - Ignore warnings and complete the actions. - This parameter is useful while removing virtual machine which is powered on state. - 'This module reflects the VMware vCenter API and UI workflow, as such, in some cases the `force` flag will be mandatory to perform the action to ensure you are certain the action has to be taken, no matter what the consequence. This is specifically the case for removing a powered on the virtual machine when C(state) is set to C(absent).' default: 'no' type: bool delete_from_inventory: description: - Whether to delete Virtual machine from inventory or delete from disk. default: False type: bool version_added: '2.10' datacenter: description: - Destination datacenter for the deploy operation. - This parameter is case sensitive. default: ha-datacenter cluster: description: - The cluster name where the virtual machine will run. - This is a required parameter, if C(esxi_hostname) is not set. - C(esxi_hostname) and C(cluster) are mutually exclusive parameters. - This parameter is case sensitive. version_added: '2.3' esxi_hostname: description: - The ESXi hostname where the virtual machine will run. - This is a required parameter, if C(cluster) is not set. - C(esxi_hostname) and C(cluster) are mutually exclusive parameters. - This parameter is case sensitive. annotation: description: - A note or annotation to include in the virtual machine. version_added: '2.3' customvalues: description: - Define a list of custom values to set on virtual machine. - A custom value object takes two fields C(key) and C(value). - Incorrect key and values will be ignored. version_added: '2.3' networks: description: - A list of networks (in the order of the NICs). - Removing NICs is not allowed, while reconfiguring the virtual machine. - All parameters and VMware object names are case sensitive. - 'One of the below parameters is required per entry:' - ' - C(name) (string): Name of the portgroup or distributed virtual portgroup for this interface. When specifying distributed virtual portgroup make sure given C(esxi_hostname) or C(cluster) is associated with it.' - ' - C(vlan) (integer): VLAN number for this interface.' - 'Optional parameters per entry (used for virtual hardware):' - ' - C(device_type) (string): Virtual network device (one of C(e1000), C(e1000e), C(pcnet32), C(vmxnet2), C(vmxnet3) (default), C(sriov)).' - ' - C(mac) (string): Customize MAC address.' - ' - C(dvswitch_name) (string): Name of the distributed vSwitch. This value is required if multiple distributed portgroups exists with the same name. version_added 2.7' - ' - C(start_connected) (bool): Indicates that virtual network adapter starts with associated virtual machine powers on. version_added: 2.5' - 'Optional parameters per entry (used for OS customization):' - ' - C(type) (string): Type of IP assignment (either C(dhcp) or C(static)). C(dhcp) is default.' - ' - C(ip) (string): Static IP address (implies C(type: static)).' - ' - C(netmask) (string): Static netmask required for C(ip).' - ' - C(gateway) (string): Static gateway.' - ' - C(dns_servers) (string): DNS servers for this network interface (Windows).' - ' - C(domain) (string): Domain name for this network interface (Windows).' - ' - C(wake_on_lan) (bool): Indicates if wake-on-LAN is enabled on this virtual network adapter. version_added: 2.5' - ' - C(allow_guest_control) (bool): Enables guest control over whether the connectable device is connected. version_added: 2.5' version_added: '2.3' customization: description: - Parameters for OS customization when cloning from the template or the virtual machine, or apply to the existing virtual machine directly. - Not all operating systems are supported for customization with respective vCenter version, please check VMware documentation for respective OS customization. - For supported customization operating system matrix, (see U(http://partnerweb.vmware.com/programs/guestOS/guest-os-customization-matrix.pdf)) - All parameters and VMware object names are case sensitive. - Linux based OSes requires Perl package to be installed for OS customizations. - 'Common parameters (Linux/Windows):' - ' - C(existing_vm) (bool): If set to C(True), do OS customization on the specified virtual machine directly. If set to C(False) or not specified, do OS customization when cloning from the template or the virtual machine. version_added: 2.8' - ' - C(dns_servers) (list): List of DNS servers to configure.' - ' - C(dns_suffix) (list): List of domain suffixes, also known as DNS search path (default: C(domain) parameter).' - ' - C(domain) (string): DNS domain name to use.' - ' - C(hostname) (string): Computer hostname (default: shorted C(name) parameter). Allowed characters are alphanumeric (uppercase and lowercase) and minus, rest of the characters are dropped as per RFC 952.' - 'Parameters related to Linux customization:' - ' - C(timezone) (string): Timezone (See List of supported time zones for different vSphere versions in Linux/Unix systems (2145518) U(https://kb.vmware.com/s/article/2145518)). version_added: 2.9' - ' - C(hwclockUTC) (bool): Specifies whether the hardware clock is in UTC or local time. True when the hardware clock is in UTC, False when the hardware clock is in local time. version_added: 2.9' - 'Parameters related to Windows customization:' - ' - C(autologon) (bool): Auto logon after virtual machine customization (default: False).' - ' - C(autologoncount) (int): Number of autologon after reboot (default: 1).' - ' - C(domainadmin) (string): User used to join in AD domain (mandatory with C(joindomain)).' - ' - C(domainadminpassword) (string): Password used to join in AD domain (mandatory with C(joindomain)).' - ' - C(fullname) (string): Server owner name (default: Administrator).' - ' - C(joindomain) (string): AD domain to join (Not compatible with C(joinworkgroup)).' - ' - C(joinworkgroup) (string): Workgroup to join (Not compatible with C(joindomain), default: WORKGROUP).' - ' - C(orgname) (string): Organisation name (default: ACME).' - ' - C(password) (string): Local administrator password.' - ' - C(productid) (string): Product ID.' - ' - C(runonce) (list): List of commands to run at first user logon.' - ' - C(timezone) (int): Timezone (See U(https://msdn.microsoft.com/en-us/library/ms912391.aspx)).' version_added: '2.3' vapp_properties: description: - A list of vApp properties - 'For full list of attributes and types refer to: U(https://github.com/vmware/pyvmomi/blob/master/docs/vim/vApp/PropertyInfo.rst)' - 'Basic attributes are:' - ' - C(id) (string): Property id - required.' - ' - C(value) (string): Property value.' - ' - C(type) (string): Value type, string type by default.' - ' - C(operation): C(remove): This attribute is required only when removing properties.' version_added: '2.6' customization_spec: description: - Unique name identifying the requested customization specification. - This parameter is case sensitive. - If set, then overrides C(customization) parameter values. version_added: '2.6' datastore: description: - Specify datastore or datastore cluster to provision virtual machine. - 'This parameter takes precedence over "disk.datastore" parameter.' - 'This parameter can be used to override datastore or datastore cluster setting of the virtual machine when deployed from the template.' - Please see example for more usage. version_added: '2.7' convert: description: - Specify convert disk type while cloning template or virtual machine. choices: [ thin, thick, eagerzeroedthick ] version_added: '2.8' extends_documentation_fragment: vmware.documentation ''' EXAMPLES = r''' - name: Create a virtual machine on given ESXi hostname vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no folder: /DC1/vm/ name: test_vm_0001 state: poweredon guest_id: centos64Guest # This is hostname of particular ESXi server on which user wants VM to be deployed esxi_hostname: "{{ esxi_hostname }}" disk: - size_gb: 10 type: thin datastore: datastore1 hardware: memory_mb: 512 num_cpus: 4 scsi: paravirtual networks: - name: VM Network mac: aa:bb:dd:aa:00:14 ip: 10.10.10.100 netmask: 255.255.255.0 device_type: vmxnet3 wait_for_ip_address: yes wait_for_ip_address_timeout: 600 delegate_to: localhost register: deploy_vm - name: Create a virtual machine from a template vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no folder: /testvms name: testvm_2 state: poweredon template: template_el7 disk: - size_gb: 10 type: thin datastore: g73_datastore hardware: memory_mb: 512 num_cpus: 6 num_cpu_cores_per_socket: 3 scsi: paravirtual memory_reservation_lock: True mem_limit: 8096 mem_reservation: 4096 cpu_limit: 8096 cpu_reservation: 4096 max_connections: 5 hotadd_cpu: True hotremove_cpu: True hotadd_memory: False version: 12 # Hardware version of virtual machine boot_firmware: "efi" cdrom: type: iso iso_path: "[datastore1] livecd.iso" networks: - name: VM Network mac: aa:bb:dd:aa:00:14 wait_for_ip_address: yes delegate_to: localhost register: deploy - name: Clone a virtual machine from Windows template and customize vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no datacenter: datacenter1 cluster: cluster name: testvm-2 template: template_windows networks: - name: VM Network ip: 192.168.1.100 netmask: 255.255.255.0 gateway: 192.168.1.1 mac: aa:bb:dd:aa:00:14 domain: my_domain dns_servers: - 192.168.1.1 - 192.168.1.2 - vlan: 1234 type: dhcp customization: autologon: yes dns_servers: - 192.168.1.1 - 192.168.1.2 domain: my_domain password: new_vm_password runonce: - powershell.exe -ExecutionPolicy Unrestricted -File C:\Windows\Temp\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP delegate_to: localhost - name: Clone a virtual machine from Linux template and customize vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no datacenter: "{{ datacenter }}" state: present folder: /DC1/vm template: "{{ template }}" name: "{{ vm_name }}" cluster: DC1_C1 networks: - name: VM Network ip: 192.168.10.11 netmask: 255.255.255.0 wait_for_ip_address: True customization: domain: "{{ guest_domain }}" dns_servers: - 8.9.9.9 - 7.8.8.9 dns_suffix: - example.com - example2.com delegate_to: localhost - name: Rename a virtual machine (requires the virtual machine's uuid) vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no uuid: "{{ vm_uuid }}" name: new_name state: present delegate_to: localhost - name: Remove a virtual machine by uuid vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no uuid: "{{ vm_uuid }}" state: absent delegate_to: localhost - name: Remove a virtual machine from inventory vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no name: vm_name delete_from_inventory: True state: absent delegate_to: localhost - name: Manipulate vApp properties vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no name: vm_name state: present vapp_properties: - id: remoteIP category: Backup label: Backup server IP type: str value: 10.10.10.1 - id: old_property operation: remove delegate_to: localhost - name: Set powerstate of a virtual machine to poweroff by using UUID vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no uuid: "{{ vm_uuid }}" state: poweredoff delegate_to: localhost - name: Deploy a virtual machine in a datastore different from the datastore of the template vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" name: "{{ vm_name }}" state: present template: "{{ template_name }}" # Here datastore can be different which holds template datastore: "{{ virtual_machine_datastore }}" hardware: memory_mb: 512 num_cpus: 2 scsi: paravirtual delegate_to: localhost ''' RETURN = r''' instance: description: metadata about the new virtual machine returned: always type: dict sample: None ''' import re import time import string HAS_PYVMOMI = False try: from pyVmomi import vim, vmodl, VmomiSupport HAS_PYVMOMI = True except ImportError: pass from random import randint from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.network import is_mac from ansible.module_utils._text import to_text, to_native from ansible.module_utils.vmware import (find_obj, gather_vm_facts, get_all_objs, compile_folder_path_for_object, serialize_spec, vmware_argument_spec, set_vm_power_state, PyVmomi, find_dvs_by_name, find_dvspg_by_name, wait_for_vm_ip, wait_for_task, TaskError) def list_or_dict(value): if isinstance(value, list) or isinstance(value, dict): return value else: raise ValueError("'%s' is not valid, valid type is 'list' or 'dict'." % value) class PyVmomiDeviceHelper(object): """ This class is a helper to create easily VMware Objects for PyVmomiHelper """ def __init__(self, module): self.module = module self.next_disk_unit_number = 0 self.scsi_device_type = { 'lsilogic': vim.vm.device.VirtualLsiLogicController, 'paravirtual': vim.vm.device.ParaVirtualSCSIController, 'buslogic': vim.vm.device.VirtualBusLogicController, 'lsilogicsas': vim.vm.device.VirtualLsiLogicSASController, } def create_scsi_controller(self, scsi_type): scsi_ctl = vim.vm.device.VirtualDeviceSpec() scsi_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add scsi_device = self.scsi_device_type.get(scsi_type, vim.vm.device.ParaVirtualSCSIController) scsi_ctl.device = scsi_device() scsi_ctl.device.busNumber = 0 # While creating a new SCSI controller, temporary key value # should be unique negative integers scsi_ctl.device.key = -randint(1000, 9999) scsi_ctl.device.hotAddRemove = True scsi_ctl.device.sharedBus = 'noSharing' scsi_ctl.device.scsiCtlrUnitNumber = 7 return scsi_ctl def is_scsi_controller(self, device): return isinstance(device, tuple(self.scsi_device_type.values())) @staticmethod def create_ide_controller(bus_number=0): ide_ctl = vim.vm.device.VirtualDeviceSpec() ide_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add ide_ctl.device = vim.vm.device.VirtualIDEController() ide_ctl.device.deviceInfo = vim.Description() # While creating a new IDE controller, temporary key value # should be unique negative integers ide_ctl.device.key = -randint(200, 299) ide_ctl.device.busNumber = bus_number return ide_ctl @staticmethod def create_cdrom(ide_device, cdrom_type, iso_path=None, unit_number=0): cdrom_spec = vim.vm.device.VirtualDeviceSpec() cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add cdrom_spec.device = vim.vm.device.VirtualCdrom() cdrom_spec.device.controllerKey = ide_device.key cdrom_spec.device.key = -randint(3000, 3999) cdrom_spec.device.unitNumber = unit_number cdrom_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo() cdrom_spec.device.connectable.allowGuestControl = True cdrom_spec.device.connectable.startConnected = (cdrom_type != "none") if cdrom_type in ["none", "client"]: cdrom_spec.device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo() elif cdrom_type == "iso": cdrom_spec.device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso_path) return cdrom_spec @staticmethod def is_equal_cdrom(vm_obj, cdrom_device, cdrom_type, iso_path): if cdrom_type == "none": return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo) and cdrom_device.connectable.allowGuestControl and not cdrom_device.connectable.startConnected and (vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or not cdrom_device.connectable.connected)) elif cdrom_type == "client": return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo) and cdrom_device.connectable.allowGuestControl and cdrom_device.connectable.startConnected and (vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or cdrom_device.connectable.connected)) elif cdrom_type == "iso": return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.IsoBackingInfo) and cdrom_device.backing.fileName == iso_path and cdrom_device.connectable.allowGuestControl and cdrom_device.connectable.startConnected and (vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or cdrom_device.connectable.connected)) @staticmethod def update_cdrom_config(vm_obj, cdrom_spec, cdrom_device, iso_path=None): # Updating an existing CD-ROM if cdrom_spec["type"] in ["client", "none"]: cdrom_device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo() elif cdrom_spec["type"] == "iso" and iso_path is not None: cdrom_device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso_path) cdrom_device.connectable = vim.vm.device.VirtualDevice.ConnectInfo() cdrom_device.connectable.allowGuestControl = True cdrom_device.connectable.startConnected = (cdrom_spec["type"] != "none") if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: cdrom_device.connectable.connected = (cdrom_spec["type"] != "none") def remove_cdrom(self, cdrom_device): cdrom_spec = vim.vm.device.VirtualDeviceSpec() cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove cdrom_spec.device = cdrom_device return cdrom_spec def create_scsi_disk(self, scsi_ctl, disk_index=None): diskspec = vim.vm.device.VirtualDeviceSpec() diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add diskspec.device = vim.vm.device.VirtualDisk() diskspec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo() diskspec.device.controllerKey = scsi_ctl.device.key if self.next_disk_unit_number == 7: raise AssertionError() if disk_index == 7: raise AssertionError() """ Configure disk unit number. """ if disk_index is not None: diskspec.device.unitNumber = disk_index self.next_disk_unit_number = disk_index + 1 else: diskspec.device.unitNumber = self.next_disk_unit_number self.next_disk_unit_number += 1 # unit number 7 is reserved to SCSI controller, increase next index if self.next_disk_unit_number == 7: self.next_disk_unit_number += 1 return diskspec def get_device(self, device_type, name): nic_dict = dict(pcnet32=vim.vm.device.VirtualPCNet32(), vmxnet2=vim.vm.device.VirtualVmxnet2(), vmxnet3=vim.vm.device.VirtualVmxnet3(), e1000=vim.vm.device.VirtualE1000(), e1000e=vim.vm.device.VirtualE1000e(), sriov=vim.vm.device.VirtualSriovEthernetCard(), ) if device_type in nic_dict: return nic_dict[device_type] else: self.module.fail_json(msg='Invalid device_type "%s"' ' for network "%s"' % (device_type, name)) def create_nic(self, device_type, device_label, device_infos): nic = vim.vm.device.VirtualDeviceSpec() nic.device = self.get_device(device_type, device_infos['name']) nic.device.wakeOnLanEnabled = bool(device_infos.get('wake_on_lan', True)) nic.device.deviceInfo = vim.Description() nic.device.deviceInfo.label = device_label nic.device.deviceInfo.summary = device_infos['name'] nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo() nic.device.connectable.startConnected = bool(device_infos.get('start_connected', True)) nic.device.connectable.allowGuestControl = bool(device_infos.get('allow_guest_control', True)) nic.device.connectable.connected = True if 'mac' in device_infos and is_mac(device_infos['mac']): nic.device.addressType = 'manual' nic.device.macAddress = device_infos['mac'] else: nic.device.addressType = 'generated' return nic def integer_value(self, input_value, name): """ Function to return int value for given input, else return error Args: input_value: Input value to retrieve int value from name: Name of the Input value (used to build error message) Returns: (int) if integer value can be obtained, otherwise will send a error message. """ if isinstance(input_value, int): return input_value elif isinstance(input_value, str) and input_value.isdigit(): return int(input_value) else: self.module.fail_json(msg='"%s" attribute should be an' ' integer value.' % name) class PyVmomiCache(object): """ This class caches references to objects which are requested multiples times but not modified """ def __init__(self, content, dc_name=None): self.content = content self.dc_name = dc_name self.networks = {} self.clusters = {} self.esx_hosts = {} self.parent_datacenters = {} def find_obj(self, content, types, name, confine_to_datacenter=True): """ Wrapper around find_obj to set datacenter context """ result = find_obj(content, types, name) if result and confine_to_datacenter: if to_text(self.get_parent_datacenter(result).name) != to_text(self.dc_name): result = None objects = self.get_all_objs(content, types, confine_to_datacenter=True) for obj in objects: if name is None or to_text(obj.name) == to_text(name): return obj return result def get_all_objs(self, content, types, confine_to_datacenter=True): """ Wrapper around get_all_objs to set datacenter context """ objects = get_all_objs(content, types) if confine_to_datacenter: if hasattr(objects, 'items'): # resource pools come back as a dictionary # make a copy for k, v in tuple(objects.items()): parent_dc = self.get_parent_datacenter(k) if parent_dc.name != self.dc_name: del objects[k] else: # everything else should be a list objects = [x for x in objects if self.get_parent_datacenter(x).name == self.dc_name] return objects def get_network(self, network): if network not in self.networks: self.networks[network] = self.find_obj(self.content, [vim.Network], network) return self.networks[network] def get_cluster(self, cluster): if cluster not in self.clusters: self.clusters[cluster] = self.find_obj(self.content, [vim.ClusterComputeResource], cluster) return self.clusters[cluster] def get_esx_host(self, host): if host not in self.esx_hosts: self.esx_hosts[host] = self.find_obj(self.content, [vim.HostSystem], host) return self.esx_hosts[host] def get_parent_datacenter(self, obj): """ Walk the parent tree to find the objects datacenter """ if isinstance(obj, vim.Datacenter): return obj if obj in self.parent_datacenters: return self.parent_datacenters[obj] datacenter = None while True: if not hasattr(obj, 'parent'): break obj = obj.parent if isinstance(obj, vim.Datacenter): datacenter = obj break self.parent_datacenters[obj] = datacenter return datacenter class PyVmomiHelper(PyVmomi): def __init__(self, module): super(PyVmomiHelper, self).__init__(module) self.device_helper = PyVmomiDeviceHelper(self.module) self.configspec = None self.relospec = None self.change_detected = False # a change was detected and needs to be applied through reconfiguration self.change_applied = False # a change was applied meaning at least one task succeeded self.customspec = None self.cache = PyVmomiCache(self.content, dc_name=self.params['datacenter']) def gather_facts(self, vm): return gather_vm_facts(self.content, vm) def remove_vm(self, vm, delete_from_inventory=False): # https://www.vmware.com/support/developer/converter-sdk/conv60_apireference/vim.ManagedEntity.html#destroy if vm.summary.runtime.powerState.lower() == 'poweredon': self.module.fail_json(msg="Virtual machine %s found in 'powered on' state, " "please use 'force' parameter to remove or poweroff VM " "and try removing VM again." % vm.name) # Delete VM from Inventory if delete_from_inventory: try: vm.UnregisterVM() except (vim.fault.TaskInProgress, vmodl.RuntimeFault) as e: return {'changed': self.change_applied, 'failed': True, 'msg': e.msg, 'op': 'UnregisterVM'} self.change_applied = True return {'changed': self.change_applied, 'failed': False} # Delete VM from Disk task = vm.Destroy() self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'destroy'} else: return {'changed': self.change_applied, 'failed': False} def configure_guestid(self, vm_obj, vm_creation=False): # guest_id is not required when using templates if self.params['template']: return # guest_id is only mandatory on VM creation if vm_creation and self.params['guest_id'] is None: self.module.fail_json(msg="guest_id attribute is mandatory for VM creation") if self.params['guest_id'] and \ (vm_obj is None or self.params['guest_id'].lower() != vm_obj.summary.config.guestId.lower()): self.change_detected = True self.configspec.guestId = self.params['guest_id'] def configure_resource_alloc_info(self, vm_obj): """ Function to configure resource allocation information about virtual machine :param vm_obj: VM object in case of reconfigure, None in case of deploy :return: None """ rai_change_detected = False memory_allocation = vim.ResourceAllocationInfo() cpu_allocation = vim.ResourceAllocationInfo() if 'hardware' in self.params: if 'mem_limit' in self.params['hardware']: mem_limit = None try: mem_limit = int(self.params['hardware'].get('mem_limit')) except ValueError: self.module.fail_json(msg="hardware.mem_limit attribute should be an integer value.") memory_allocation.limit = mem_limit if vm_obj is None or memory_allocation.limit != vm_obj.config.memoryAllocation.limit: rai_change_detected = True if 'mem_reservation' in self.params['hardware'] or 'memory_reservation' in self.params['hardware']: mem_reservation = self.params['hardware'].get('mem_reservation') if mem_reservation is None: mem_reservation = self.params['hardware'].get('memory_reservation') try: mem_reservation = int(mem_reservation) except ValueError: self.module.fail_json(msg="hardware.mem_reservation or hardware.memory_reservation should be an integer value.") memory_allocation.reservation = mem_reservation if vm_obj is None or \ memory_allocation.reservation != vm_obj.config.memoryAllocation.reservation: rai_change_detected = True if 'cpu_limit' in self.params['hardware']: cpu_limit = None try: cpu_limit = int(self.params['hardware'].get('cpu_limit')) except ValueError: self.module.fail_json(msg="hardware.cpu_limit attribute should be an integer value.") cpu_allocation.limit = cpu_limit if vm_obj is None or cpu_allocation.limit != vm_obj.config.cpuAllocation.limit: rai_change_detected = True if 'cpu_reservation' in self.params['hardware']: cpu_reservation = None try: cpu_reservation = int(self.params['hardware'].get('cpu_reservation')) except ValueError: self.module.fail_json(msg="hardware.cpu_reservation should be an integer value.") cpu_allocation.reservation = cpu_reservation if vm_obj is None or \ cpu_allocation.reservation != vm_obj.config.cpuAllocation.reservation: rai_change_detected = True if rai_change_detected: self.configspec.memoryAllocation = memory_allocation self.configspec.cpuAllocation = cpu_allocation self.change_detected = True def configure_cpu_and_memory(self, vm_obj, vm_creation=False): # set cpu/memory/etc if 'hardware' in self.params: if 'num_cpus' in self.params['hardware']: try: num_cpus = int(self.params['hardware']['num_cpus']) except ValueError: self.module.fail_json(msg="hardware.num_cpus attribute should be an integer value.") # check VM power state and cpu hot-add/hot-remove state before re-config VM if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: if not vm_obj.config.cpuHotRemoveEnabled and num_cpus < vm_obj.config.hardware.numCPU: self.module.fail_json(msg="Configured cpu number is less than the cpu number of the VM, " "cpuHotRemove is not enabled") if not vm_obj.config.cpuHotAddEnabled and num_cpus > vm_obj.config.hardware.numCPU: self.module.fail_json(msg="Configured cpu number is more than the cpu number of the VM, " "cpuHotAdd is not enabled") if 'num_cpu_cores_per_socket' in self.params['hardware']: try: num_cpu_cores_per_socket = int(self.params['hardware']['num_cpu_cores_per_socket']) except ValueError: self.module.fail_json(msg="hardware.num_cpu_cores_per_socket attribute " "should be an integer value.") if num_cpus % num_cpu_cores_per_socket != 0: self.module.fail_json(msg="hardware.num_cpus attribute should be a multiple " "of hardware.num_cpu_cores_per_socket") self.configspec.numCoresPerSocket = num_cpu_cores_per_socket if vm_obj is None or self.configspec.numCoresPerSocket != vm_obj.config.hardware.numCoresPerSocket: self.change_detected = True self.configspec.numCPUs = num_cpus if vm_obj is None or self.configspec.numCPUs != vm_obj.config.hardware.numCPU: self.change_detected = True # num_cpu is mandatory for VM creation elif vm_creation and not self.params['template']: self.module.fail_json(msg="hardware.num_cpus attribute is mandatory for VM creation") if 'memory_mb' in self.params['hardware']: try: memory_mb = int(self.params['hardware']['memory_mb']) except ValueError: self.module.fail_json(msg="Failed to parse hardware.memory_mb value." " Please refer the documentation and provide" " correct value.") # check VM power state and memory hotadd state before re-config VM if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: if vm_obj.config.memoryHotAddEnabled and memory_mb < vm_obj.config.hardware.memoryMB: self.module.fail_json(msg="Configured memory is less than memory size of the VM, " "operation is not supported") elif not vm_obj.config.memoryHotAddEnabled and memory_mb != vm_obj.config.hardware.memoryMB: self.module.fail_json(msg="memoryHotAdd is not enabled") self.configspec.memoryMB = memory_mb if vm_obj is None or self.configspec.memoryMB != vm_obj.config.hardware.memoryMB: self.change_detected = True # memory_mb is mandatory for VM creation elif vm_creation and not self.params['template']: self.module.fail_json(msg="hardware.memory_mb attribute is mandatory for VM creation") if 'hotadd_memory' in self.params['hardware']: if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \ vm_obj.config.memoryHotAddEnabled != bool(self.params['hardware']['hotadd_memory']): self.module.fail_json(msg="Configure hotadd memory operation is not supported when VM is power on") self.configspec.memoryHotAddEnabled = bool(self.params['hardware']['hotadd_memory']) if vm_obj is None or self.configspec.memoryHotAddEnabled != vm_obj.config.memoryHotAddEnabled: self.change_detected = True if 'hotadd_cpu' in self.params['hardware']: if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \ vm_obj.config.cpuHotAddEnabled != bool(self.params['hardware']['hotadd_cpu']): self.module.fail_json(msg="Configure hotadd cpu operation is not supported when VM is power on") self.configspec.cpuHotAddEnabled = bool(self.params['hardware']['hotadd_cpu']) if vm_obj is None or self.configspec.cpuHotAddEnabled != vm_obj.config.cpuHotAddEnabled: self.change_detected = True if 'hotremove_cpu' in self.params['hardware']: if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \ vm_obj.config.cpuHotRemoveEnabled != bool(self.params['hardware']['hotremove_cpu']): self.module.fail_json(msg="Configure hotremove cpu operation is not supported when VM is power on") self.configspec.cpuHotRemoveEnabled = bool(self.params['hardware']['hotremove_cpu']) if vm_obj is None or self.configspec.cpuHotRemoveEnabled != vm_obj.config.cpuHotRemoveEnabled: self.change_detected = True if 'memory_reservation_lock' in self.params['hardware']: self.configspec.memoryReservationLockedToMax = bool(self.params['hardware']['memory_reservation_lock']) if vm_obj is None or self.configspec.memoryReservationLockedToMax != vm_obj.config.memoryReservationLockedToMax: self.change_detected = True if 'boot_firmware' in self.params['hardware']: # boot firmware re-config can cause boot issue if vm_obj is not None: return boot_firmware = self.params['hardware']['boot_firmware'].lower() if boot_firmware not in ('bios', 'efi'): self.module.fail_json(msg="hardware.boot_firmware value is invalid [%s]." " Need one of ['bios', 'efi']." % boot_firmware) self.configspec.firmware = boot_firmware self.change_detected = True def sanitize_cdrom_params(self): # cdroms {'ide': [{num: 0, cdrom: []}, {}], 'sata': [{num: 0, cdrom: []}, {}, ...]} cdroms = {'ide': [], 'sata': []} expected_cdrom_spec = self.params.get('cdrom') if expected_cdrom_spec: for cdrom_spec in expected_cdrom_spec: cdrom_spec['controller_type'] = cdrom_spec.get('controller_type', 'ide').lower() if cdrom_spec['controller_type'] not in ['ide', 'sata']: self.module.fail_json(msg="Invalid cdrom.controller_type: %s, valid value is 'ide' or 'sata'." % cdrom_spec['controller_type']) cdrom_spec['state'] = cdrom_spec.get('state', 'present').lower() if cdrom_spec['state'] not in ['present', 'absent']: self.module.fail_json(msg="Invalid cdrom.state: %s, valid value is 'present', 'absent'." % cdrom_spec['state']) if cdrom_spec['state'] == 'present': if 'type' in cdrom_spec and cdrom_spec.get('type') not in ['none', 'client', 'iso']: self.module.fail_json(msg="Invalid cdrom.type: %s, valid value is 'none', 'client' or 'iso'." % cdrom_spec.get('type')) if cdrom_spec.get('type') == 'iso' and not cdrom_spec.get('iso_path'): self.module.fail_json(msg="cdrom.iso_path is mandatory when cdrom.type is set to iso.") if cdrom_spec['controller_type'] == 'ide' and \ (cdrom_spec.get('controller_number') not in [0, 1] or cdrom_spec.get('unit_number') not in [0, 1]): self.module.fail_json(msg="Invalid cdrom.controller_number: %s or cdrom.unit_number: %s, valid" " values are 0 or 1 for IDE controller." % (cdrom_spec.get('controller_number'), cdrom_spec.get('unit_number'))) if cdrom_spec['controller_type'] == 'sata' and \ (cdrom_spec.get('controller_number') not in range(0, 4) or cdrom_spec.get('unit_number') not in range(0, 30)): self.module.fail_json(msg="Invalid cdrom.controller_number: %s or cdrom.unit_number: %s," " valid controller_number value is 0-3, valid unit_number is 0-29" " for SATA controller." % (cdrom_spec.get('controller_number'), cdrom_spec.get('unit_number'))) ctl_exist = False for exist_spec in cdroms.get(cdrom_spec['controller_type']): if exist_spec['num'] == cdrom_spec['controller_number']: ctl_exist = True exist_spec['cdrom'].append(cdrom_spec) break if not ctl_exist: cdroms.get(cdrom_spec['controller_type']).append({'num': cdrom_spec['controller_number'], 'cdrom': [cdrom_spec]}) return cdroms def configure_cdrom(self, vm_obj): # Configure the VM CD-ROM if self.params.get('cdrom'): if vm_obj and vm_obj.config.template: # Changing CD-ROM settings on a template is not supported return if isinstance(self.params.get('cdrom'), dict): self.configure_cdrom_dict(vm_obj) elif isinstance(self.params.get('cdrom'), list): self.configure_cdrom_list(vm_obj) def configure_cdrom_dict(self, vm_obj): if self.params["cdrom"].get('type') not in ['none', 'client', 'iso']: self.module.fail_json(msg="cdrom.type is mandatory. Options are 'none', 'client', and 'iso'.") if self.params["cdrom"]['type'] == 'iso' and not self.params["cdrom"].get('iso_path'): self.module.fail_json(msg="cdrom.iso_path is mandatory when cdrom.type is set to iso.") cdrom_spec = None cdrom_devices = self.get_vm_cdrom_devices(vm=vm_obj) iso_path = self.params["cdrom"].get("iso_path") if len(cdrom_devices) == 0: # Creating new CD-ROM ide_devices = self.get_vm_ide_devices(vm=vm_obj) if len(ide_devices) == 0: # Creating new IDE device ide_ctl = self.device_helper.create_ide_controller() ide_device = ide_ctl.device self.change_detected = True self.configspec.deviceChange.append(ide_ctl) else: ide_device = ide_devices[0] if len(ide_device.device) > 3: self.module.fail_json(msg="hardware.cdrom specified for a VM or template which already has 4" " IDE devices of which none are a cdrom") cdrom_spec = self.device_helper.create_cdrom(ide_device=ide_device, cdrom_type=self.params["cdrom"]["type"], iso_path=iso_path) if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: cdrom_spec.device.connectable.connected = (self.params["cdrom"]["type"] != "none") elif not self.device_helper.is_equal_cdrom(vm_obj=vm_obj, cdrom_device=cdrom_devices[0], cdrom_type=self.params["cdrom"]["type"], iso_path=iso_path): self.device_helper.update_cdrom_config(vm_obj, self.params["cdrom"], cdrom_devices[0], iso_path=iso_path) cdrom_spec = vim.vm.device.VirtualDeviceSpec() cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit cdrom_spec.device = cdrom_devices[0] if cdrom_spec: self.change_detected = True self.configspec.deviceChange.append(cdrom_spec) def configure_cdrom_list(self, vm_obj): configured_cdroms = self.sanitize_cdrom_params() cdrom_devices = self.get_vm_cdrom_devices(vm=vm_obj) # configure IDE CD-ROMs if configured_cdroms['ide']: ide_devices = self.get_vm_ide_devices(vm=vm_obj) for expected_cdrom_spec in configured_cdroms['ide']: ide_device = None for device in ide_devices: if device.busNumber == expected_cdrom_spec['num']: ide_device = device break # if not find the matched ide controller or no existing ide controller if not ide_device: ide_ctl = self.device_helper.create_ide_controller(bus_number=expected_cdrom_spec['num']) ide_device = ide_ctl.device self.change_detected = True self.configspec.deviceChange.append(ide_ctl) for cdrom in expected_cdrom_spec['cdrom']: cdrom_device = None iso_path = cdrom.get('iso_path') unit_number = cdrom.get('unit_number') for target_cdrom in cdrom_devices: if target_cdrom.controllerKey == ide_device.key and target_cdrom.unitNumber == unit_number: cdrom_device = target_cdrom break # create new CD-ROM if not cdrom_device and cdrom.get('state') != 'absent': if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: self.module.fail_json(msg='CD-ROM attach to IDE controller not support hot-add.') if len(ide_device.device) == 2: self.module.fail_json(msg='Maximum number of CD-ROMs attached to IDE controller is 2.') cdrom_spec = self.device_helper.create_cdrom(ide_device=ide_device, cdrom_type=cdrom['type'], iso_path=iso_path, unit_number=unit_number) self.change_detected = True self.configspec.deviceChange.append(cdrom_spec) # re-configure CD-ROM elif cdrom_device and cdrom.get('state') != 'absent' and \ not self.device_helper.is_equal_cdrom(vm_obj=vm_obj, cdrom_device=cdrom_device, cdrom_type=cdrom['type'], iso_path=iso_path): self.device_helper.update_cdrom_config(vm_obj, cdrom, cdrom_device, iso_path=iso_path) cdrom_spec = vim.vm.device.VirtualDeviceSpec() cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit cdrom_spec.device = cdrom_device self.change_detected = True self.configspec.deviceChange.append(cdrom_spec) # delete CD-ROM elif cdrom_device and cdrom.get('state') == 'absent': if vm_obj and vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOff: self.module.fail_json(msg='CD-ROM attach to IDE controller not support hot-remove.') cdrom_spec = self.device_helper.remove_cdrom(cdrom_device) self.change_detected = True self.configspec.deviceChange.append(cdrom_spec) # configure SATA CD-ROMs is not supported yet if configured_cdroms['sata']: pass def configure_hardware_params(self, vm_obj): """ Function to configure hardware related configuration of virtual machine Args: vm_obj: virtual machine object """ if 'hardware' in self.params: if 'max_connections' in self.params['hardware']: # maxMksConnections == max_connections self.configspec.maxMksConnections = int(self.params['hardware']['max_connections']) if vm_obj is None or self.configspec.maxMksConnections != vm_obj.config.maxMksConnections: self.change_detected = True if 'nested_virt' in self.params['hardware']: self.configspec.nestedHVEnabled = bool(self.params['hardware']['nested_virt']) if vm_obj is None or self.configspec.nestedHVEnabled != bool(vm_obj.config.nestedHVEnabled): self.change_detected = True if 'version' in self.params['hardware']: hw_version_check_failed = False temp_version = self.params['hardware'].get('version', 10) if temp_version.lower() == 'latest': # Check is to make sure vm_obj is not of type template if vm_obj and not vm_obj.config.template: try: task = vm_obj.UpgradeVM_Task() self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'upgrade'} except vim.fault.AlreadyUpgraded: # Don't fail if VM is already upgraded. pass else: try: temp_version = int(temp_version) except ValueError: hw_version_check_failed = True if temp_version not in range(3, 16): hw_version_check_failed = True if hw_version_check_failed: self.module.fail_json(msg="Failed to set hardware.version '%s' value as valid" " values range from 3 (ESX 2.x) to 14 (ESXi 6.5 and greater)." % temp_version) # Hardware version is denoted as "vmx-10" version = "vmx-%02d" % temp_version self.configspec.version = version if vm_obj is None or self.configspec.version != vm_obj.config.version: self.change_detected = True # Check is to make sure vm_obj is not of type template if vm_obj and not vm_obj.config.template: # VM exists and we need to update the hardware version current_version = vm_obj.config.version # current_version = "vmx-10" version_digit = int(current_version.split("-", 1)[-1]) if temp_version < version_digit: self.module.fail_json(msg="Current hardware version '%d' which is greater than the specified" " version '%d'. Downgrading hardware version is" " not supported. Please specify version greater" " than the current version." % (version_digit, temp_version)) new_version = "vmx-%02d" % temp_version try: task = vm_obj.UpgradeVM_Task(new_version) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'upgrade'} except vim.fault.AlreadyUpgraded: # Don't fail if VM is already upgraded. pass if 'virt_based_security' in self.params['hardware']: host_version = self.select_host().summary.config.product.version if int(host_version.split('.')[0]) < 6 or (int(host_version.split('.')[0]) == 6 and int(host_version.split('.')[1]) < 7): self.module.fail_json(msg="ESXi version %s not support VBS." % host_version) guest_ids = ['windows9_64Guest', 'windows9Server64Guest'] if vm_obj is None: guestid = self.configspec.guestId else: guestid = vm_obj.summary.config.guestId if guestid not in guest_ids: self.module.fail_json(msg="Guest '%s' not support VBS." % guestid) if (vm_obj is None and int(self.configspec.version.split('-')[1]) >= 14) or \ (vm_obj and int(vm_obj.config.version.split('-')[1]) >= 14 and (vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOff)): self.configspec.flags = vim.vm.FlagInfo() self.configspec.flags.vbsEnabled = bool(self.params['hardware']['virt_based_security']) if bool(self.params['hardware']['virt_based_security']): self.configspec.flags.vvtdEnabled = True self.configspec.nestedHVEnabled = True if (vm_obj is None and self.configspec.firmware == 'efi') or \ (vm_obj and vm_obj.config.firmware == 'efi'): self.configspec.bootOptions = vim.vm.BootOptions() self.configspec.bootOptions.efiSecureBootEnabled = True else: self.module.fail_json(msg="Not support VBS when firmware is BIOS.") if vm_obj is None or self.configspec.flags.vbsEnabled != vm_obj.config.flags.vbsEnabled: self.change_detected = True def get_device_by_type(self, vm=None, type=None): device_list = [] if vm is None or type is None: return device_list for device in vm.config.hardware.device: if isinstance(device, type): device_list.append(device) return device_list def get_vm_cdrom_devices(self, vm=None): return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualCdrom) def get_vm_ide_devices(self, vm=None): return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualIDEController) def get_vm_network_interfaces(self, vm=None): device_list = [] if vm is None: return device_list nw_device_types = (vim.vm.device.VirtualPCNet32, vim.vm.device.VirtualVmxnet2, vim.vm.device.VirtualVmxnet3, vim.vm.device.VirtualE1000, vim.vm.device.VirtualE1000e, vim.vm.device.VirtualSriovEthernetCard) for device in vm.config.hardware.device: if isinstance(device, nw_device_types): device_list.append(device) return device_list def sanitize_network_params(self): """ Sanitize user provided network provided params Returns: A sanitized list of network params, else fails """ network_devices = list() # Clean up user data here for network in self.params['networks']: if 'name' not in network and 'vlan' not in network: self.module.fail_json(msg="Please specify at least a network name or" " a VLAN name under VM network list.") if 'name' in network and self.cache.get_network(network['name']) is None: self.module.fail_json(msg="Network '%(name)s' does not exist." % network) elif 'vlan' in network: dvps = self.cache.get_all_objs(self.content, [vim.dvs.DistributedVirtualPortgroup]) for dvp in dvps: if hasattr(dvp.config.defaultPortConfig, 'vlan') and \ isinstance(dvp.config.defaultPortConfig.vlan.vlanId, int) and \ str(dvp.config.defaultPortConfig.vlan.vlanId) == str(network['vlan']): network['name'] = dvp.config.name break if 'dvswitch_name' in network and \ dvp.config.distributedVirtualSwitch.name == network['dvswitch_name'] and \ dvp.config.name == network['vlan']: network['name'] = dvp.config.name break if dvp.config.name == network['vlan']: network['name'] = dvp.config.name break else: self.module.fail_json(msg="VLAN '%(vlan)s' does not exist." % network) if 'type' in network: if network['type'] not in ['dhcp', 'static']: self.module.fail_json(msg="Network type '%(type)s' is not a valid parameter." " Valid parameters are ['dhcp', 'static']." % network) if network['type'] != 'static' and ('ip' in network or 'netmask' in network): self.module.fail_json(msg='Static IP information provided for network "%(name)s",' ' but "type" is set to "%(type)s".' % network) else: # Type is optional parameter, if user provided IP or Subnet assume # network type as 'static' if 'ip' in network or 'netmask' in network: network['type'] = 'static' else: # User wants network type as 'dhcp' network['type'] = 'dhcp' if network.get('type') == 'static': if 'ip' in network and 'netmask' not in network: self.module.fail_json(msg="'netmask' is required if 'ip' is" " specified under VM network list.") if 'ip' not in network and 'netmask' in network: self.module.fail_json(msg="'ip' is required if 'netmask' is" " specified under VM network list.") validate_device_types = ['pcnet32', 'vmxnet2', 'vmxnet3', 'e1000', 'e1000e', 'sriov'] if 'device_type' in network and network['device_type'] not in validate_device_types: self.module.fail_json(msg="Device type specified '%s' is not valid." " Please specify correct device" " type from ['%s']." % (network['device_type'], "', '".join(validate_device_types))) if 'mac' in network and not is_mac(network['mac']): self.module.fail_json(msg="Device MAC address '%s' is invalid." " Please provide correct MAC address." % network['mac']) network_devices.append(network) return network_devices def configure_network(self, vm_obj): # Ignore empty networks, this permits to keep networks when deploying a template/cloning a VM if len(self.params['networks']) == 0: return network_devices = self.sanitize_network_params() # List current device for Clone or Idempotency current_net_devices = self.get_vm_network_interfaces(vm=vm_obj) if len(network_devices) < len(current_net_devices): self.module.fail_json(msg="Given network device list is lesser than current VM device list (%d < %d). " "Removing interfaces is not allowed" % (len(network_devices), len(current_net_devices))) for key in range(0, len(network_devices)): nic_change_detected = False network_name = network_devices[key]['name'] if key < len(current_net_devices) and (vm_obj or self.params['template']): # We are editing existing network devices, this is either when # are cloning from VM or Template nic = vim.vm.device.VirtualDeviceSpec() nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit nic.device = current_net_devices[key] if ('wake_on_lan' in network_devices[key] and nic.device.wakeOnLanEnabled != network_devices[key].get('wake_on_lan')): nic.device.wakeOnLanEnabled = network_devices[key].get('wake_on_lan') nic_change_detected = True if ('start_connected' in network_devices[key] and nic.device.connectable.startConnected != network_devices[key].get('start_connected')): nic.device.connectable.startConnected = network_devices[key].get('start_connected') nic_change_detected = True if ('allow_guest_control' in network_devices[key] and nic.device.connectable.allowGuestControl != network_devices[key].get('allow_guest_control')): nic.device.connectable.allowGuestControl = network_devices[key].get('allow_guest_control') nic_change_detected = True if nic.device.deviceInfo.summary != network_name: nic.device.deviceInfo.summary = network_name nic_change_detected = True if 'device_type' in network_devices[key]: device = self.device_helper.get_device(network_devices[key]['device_type'], network_name) device_class = type(device) if not isinstance(nic.device, device_class): self.module.fail_json(msg="Changing the device type is not possible when interface is already present. " "The failing device type is %s" % network_devices[key]['device_type']) # Changing mac address has no effect when editing interface if 'mac' in network_devices[key] and nic.device.macAddress != current_net_devices[key].macAddress: self.module.fail_json(msg="Changing MAC address has not effect when interface is already present. " "The failing new MAC address is %s" % nic.device.macAddress) else: # Default device type is vmxnet3, VMware best practice device_type = network_devices[key].get('device_type', 'vmxnet3') nic = self.device_helper.create_nic(device_type, 'Network Adapter %s' % (key + 1), network_devices[key]) nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add nic_change_detected = True if hasattr(self.cache.get_network(network_name), 'portKeys'): # VDS switch pg_obj = None if 'dvswitch_name' in network_devices[key]: dvs_name = network_devices[key]['dvswitch_name'] dvs_obj = find_dvs_by_name(self.content, dvs_name) if dvs_obj is None: self.module.fail_json(msg="Unable to find distributed virtual switch %s" % dvs_name) pg_obj = find_dvspg_by_name(dvs_obj, network_name) if pg_obj is None: self.module.fail_json(msg="Unable to find distributed port group %s" % network_name) else: pg_obj = self.cache.find_obj(self.content, [vim.dvs.DistributedVirtualPortgroup], network_name) # TODO: (akasurde) There is no way to find association between resource pool and distributed virtual portgroup # For now, check if we are able to find distributed virtual switch if not pg_obj.config.distributedVirtualSwitch: self.module.fail_json(msg="Failed to find distributed virtual switch which is associated with" " distributed virtual portgroup '%s'. Make sure hostsystem is associated with" " the given distributed virtual portgroup. Also, check if user has correct" " permission to access distributed virtual switch in the given portgroup." % pg_obj.name) if (nic.device.backing and (not hasattr(nic.device.backing, 'port') or (nic.device.backing.port.portgroupKey != pg_obj.key or nic.device.backing.port.switchUuid != pg_obj.config.distributedVirtualSwitch.uuid))): nic_change_detected = True dvs_port_connection = vim.dvs.PortConnection() dvs_port_connection.portgroupKey = pg_obj.key # If user specifies distributed port group without associating to the hostsystem on which # virtual machine is going to be deployed then we get error. We can infer that there is no # association between given distributed port group and host system. host_system = self.params.get('esxi_hostname') if host_system and host_system not in [host.config.host.name for host in pg_obj.config.distributedVirtualSwitch.config.host]: self.module.fail_json(msg="It seems that host system '%s' is not associated with distributed" " virtual portgroup '%s'. Please make sure host system is associated" " with given distributed virtual portgroup" % (host_system, pg_obj.name)) dvs_port_connection.switchUuid = pg_obj.config.distributedVirtualSwitch.uuid nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo() nic.device.backing.port = dvs_port_connection elif isinstance(self.cache.get_network(network_name), vim.OpaqueNetwork): # NSX-T Logical Switch nic.device.backing = vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo() network_id = self.cache.get_network(network_name).summary.opaqueNetworkId nic.device.backing.opaqueNetworkType = 'nsx.LogicalSwitch' nic.device.backing.opaqueNetworkId = network_id nic.device.deviceInfo.summary = 'nsx.LogicalSwitch: %s' % network_id nic_change_detected = True else: # vSwitch if not isinstance(nic.device.backing, vim.vm.device.VirtualEthernetCard.NetworkBackingInfo): nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo() nic_change_detected = True net_obj = self.cache.get_network(network_name) if nic.device.backing.network != net_obj: nic.device.backing.network = net_obj nic_change_detected = True if nic.device.backing.deviceName != network_name: nic.device.backing.deviceName = network_name nic_change_detected = True if nic_change_detected: # Change to fix the issue found while configuring opaque network # VMs cloned from a template with opaque network will get disconnected # Replacing deprecated config parameter with relocation Spec if isinstance(self.cache.get_network(network_name), vim.OpaqueNetwork): self.relospec.deviceChange.append(nic) else: self.configspec.deviceChange.append(nic) self.change_detected = True def configure_vapp_properties(self, vm_obj): if len(self.params['vapp_properties']) == 0: return for x in self.params['vapp_properties']: if not x.get('id'): self.module.fail_json(msg="id is required to set vApp property") new_vmconfig_spec = vim.vApp.VmConfigSpec() if vm_obj: # VM exists # This is primarily for vcsim/integration tests, unset vAppConfig was not seen on my deployments orig_spec = vm_obj.config.vAppConfig if vm_obj.config.vAppConfig else new_vmconfig_spec vapp_properties_current = dict((x.id, x) for x in orig_spec.property) vapp_properties_to_change = dict((x['id'], x) for x in self.params['vapp_properties']) # each property must have a unique key # init key counter with max value + 1 all_keys = [x.key for x in orig_spec.property] new_property_index = max(all_keys) + 1 if all_keys else 0 for property_id, property_spec in vapp_properties_to_change.items(): is_property_changed = False new_vapp_property_spec = vim.vApp.PropertySpec() if property_id in vapp_properties_current: if property_spec.get('operation') == 'remove': new_vapp_property_spec.operation = 'remove' new_vapp_property_spec.removeKey = vapp_properties_current[property_id].key is_property_changed = True else: # this is 'edit' branch new_vapp_property_spec.operation = 'edit' new_vapp_property_spec.info = vapp_properties_current[property_id] try: for property_name, property_value in property_spec.items(): if property_name == 'operation': # operation is not an info object property # if set to anything other than 'remove' we don't fail continue # Updating attributes only if needed if getattr(new_vapp_property_spec.info, property_name) != property_value: setattr(new_vapp_property_spec.info, property_name, property_value) is_property_changed = True except Exception as e: msg = "Failed to set vApp property field='%s' and value='%s'. Error: %s" % (property_name, property_value, to_text(e)) self.module.fail_json(msg=msg) else: if property_spec.get('operation') == 'remove': # attempt to delete non-existent property continue # this is add new property branch new_vapp_property_spec.operation = 'add' property_info = vim.vApp.PropertyInfo() property_info.classId = property_spec.get('classId') property_info.instanceId = property_spec.get('instanceId') property_info.id = property_spec.get('id') property_info.category = property_spec.get('category') property_info.label = property_spec.get('label') property_info.type = property_spec.get('type', 'string') property_info.userConfigurable = property_spec.get('userConfigurable', True) property_info.defaultValue = property_spec.get('defaultValue') property_info.value = property_spec.get('value', '') property_info.description = property_spec.get('description') new_vapp_property_spec.info = property_info new_vapp_property_spec.info.key = new_property_index new_property_index += 1 is_property_changed = True if is_property_changed: new_vmconfig_spec.property.append(new_vapp_property_spec) else: # New VM all_keys = [x.key for x in new_vmconfig_spec.property] new_property_index = max(all_keys) + 1 if all_keys else 0 vapp_properties_to_change = dict((x['id'], x) for x in self.params['vapp_properties']) is_property_changed = False for property_id, property_spec in vapp_properties_to_change.items(): new_vapp_property_spec = vim.vApp.PropertySpec() # this is add new property branch new_vapp_property_spec.operation = 'add' property_info = vim.vApp.PropertyInfo() property_info.classId = property_spec.get('classId') property_info.instanceId = property_spec.get('instanceId') property_info.id = property_spec.get('id') property_info.category = property_spec.get('category') property_info.label = property_spec.get('label') property_info.type = property_spec.get('type', 'string') property_info.userConfigurable = property_spec.get('userConfigurable', True) property_info.defaultValue = property_spec.get('defaultValue') property_info.value = property_spec.get('value', '') property_info.description = property_spec.get('description') new_vapp_property_spec.info = property_info new_vapp_property_spec.info.key = new_property_index new_property_index += 1 is_property_changed = True if is_property_changed: new_vmconfig_spec.property.append(new_vapp_property_spec) if new_vmconfig_spec.property: self.configspec.vAppConfig = new_vmconfig_spec self.change_detected = True def customize_customvalues(self, vm_obj): if len(self.params['customvalues']) == 0: return facts = self.gather_facts(vm_obj) for kv in self.params['customvalues']: if 'key' not in kv or 'value' not in kv: self.module.exit_json(msg="customvalues items required both 'key' and 'value' fields.") key_id = None for field in self.content.customFieldsManager.field: if field.name == kv['key']: key_id = field.key break if not key_id: self.module.fail_json(msg="Unable to find custom value key %s" % kv['key']) # If kv is not kv fetched from facts, change it if kv['key'] not in facts['customvalues'] or facts['customvalues'][kv['key']] != kv['value']: self.content.customFieldsManager.SetField(entity=vm_obj, key=key_id, value=kv['value']) self.change_detected = True def customize_vm(self, vm_obj): # User specified customization specification custom_spec_name = self.params.get('customization_spec') if custom_spec_name: cc_mgr = self.content.customizationSpecManager if cc_mgr.DoesCustomizationSpecExist(name=custom_spec_name): temp_spec = cc_mgr.GetCustomizationSpec(name=custom_spec_name) self.customspec = temp_spec.spec return else: self.module.fail_json(msg="Unable to find customization specification" " '%s' in given configuration." % custom_spec_name) # Network settings adaptermaps = [] for network in self.params['networks']: guest_map = vim.vm.customization.AdapterMapping() guest_map.adapter = vim.vm.customization.IPSettings() if 'ip' in network and 'netmask' in network: guest_map.adapter.ip = vim.vm.customization.FixedIp() guest_map.adapter.ip.ipAddress = str(network['ip']) guest_map.adapter.subnetMask = str(network['netmask']) elif 'type' in network and network['type'] == 'dhcp': guest_map.adapter.ip = vim.vm.customization.DhcpIpGenerator() if 'gateway' in network: guest_map.adapter.gateway = network['gateway'] # On Windows, DNS domain and DNS servers can be set by network interface # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.IPSettings.html if 'domain' in network: guest_map.adapter.dnsDomain = network['domain'] elif 'domain' in self.params['customization']: guest_map.adapter.dnsDomain = self.params['customization']['domain'] if 'dns_servers' in network: guest_map.adapter.dnsServerList = network['dns_servers'] elif 'dns_servers' in self.params['customization']: guest_map.adapter.dnsServerList = self.params['customization']['dns_servers'] adaptermaps.append(guest_map) # Global DNS settings globalip = vim.vm.customization.GlobalIPSettings() if 'dns_servers' in self.params['customization']: globalip.dnsServerList = self.params['customization']['dns_servers'] # TODO: Maybe list the different domains from the interfaces here by default ? if 'dns_suffix' in self.params['customization']: dns_suffix = self.params['customization']['dns_suffix'] if isinstance(dns_suffix, list): globalip.dnsSuffixList = " ".join(dns_suffix) else: globalip.dnsSuffixList = dns_suffix elif 'domain' in self.params['customization']: globalip.dnsSuffixList = self.params['customization']['domain'] if self.params['guest_id']: guest_id = self.params['guest_id'] else: guest_id = vm_obj.summary.config.guestId # For windows guest OS, use SysPrep # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.Sysprep.html#field_detail if 'win' in guest_id: ident = vim.vm.customization.Sysprep() ident.userData = vim.vm.customization.UserData() # Setting hostName, orgName and fullName is mandatory, so we set some default when missing ident.userData.computerName = vim.vm.customization.FixedName() # computer name will be truncated to 15 characters if using VM name default_name = self.params['name'].replace(' ', '') default_name = ''.join([c for c in default_name if c not in string.punctuation]) ident.userData.computerName.name = str(self.params['customization'].get('hostname', default_name[0:15])) ident.userData.fullName = str(self.params['customization'].get('fullname', 'Administrator')) ident.userData.orgName = str(self.params['customization'].get('orgname', 'ACME')) if 'productid' in self.params['customization']: ident.userData.productId = str(self.params['customization']['productid']) ident.guiUnattended = vim.vm.customization.GuiUnattended() if 'autologon' in self.params['customization']: ident.guiUnattended.autoLogon = self.params['customization']['autologon'] ident.guiUnattended.autoLogonCount = self.params['customization'].get('autologoncount', 1) if 'timezone' in self.params['customization']: # Check if timezone value is a int before proceeding. ident.guiUnattended.timeZone = self.device_helper.integer_value( self.params['customization']['timezone'], 'customization.timezone') ident.identification = vim.vm.customization.Identification() if self.params['customization'].get('password', '') != '': ident.guiUnattended.password = vim.vm.customization.Password() ident.guiUnattended.password.value = str(self.params['customization']['password']) ident.guiUnattended.password.plainText = True if 'joindomain' in self.params['customization']: if 'domainadmin' not in self.params['customization'] or 'domainadminpassword' not in self.params['customization']: self.module.fail_json(msg="'domainadmin' and 'domainadminpassword' entries are mandatory in 'customization' section to use " "joindomain feature") ident.identification.domainAdmin = str(self.params['customization']['domainadmin']) ident.identification.joinDomain = str(self.params['customization']['joindomain']) ident.identification.domainAdminPassword = vim.vm.customization.Password() ident.identification.domainAdminPassword.value = str(self.params['customization']['domainadminpassword']) ident.identification.domainAdminPassword.plainText = True elif 'joinworkgroup' in self.params['customization']: ident.identification.joinWorkgroup = str(self.params['customization']['joinworkgroup']) if 'runonce' in self.params['customization']: ident.guiRunOnce = vim.vm.customization.GuiRunOnce() ident.guiRunOnce.commandList = self.params['customization']['runonce'] else: # FIXME: We have no clue whether this non-Windows OS is actually Linux, hence it might fail! # For Linux guest OS, use LinuxPrep # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.LinuxPrep.html ident = vim.vm.customization.LinuxPrep() # TODO: Maybe add domain from interface if missing ? if 'domain' in self.params['customization']: ident.domain = str(self.params['customization']['domain']) ident.hostName = vim.vm.customization.FixedName() hostname = str(self.params['customization'].get('hostname', self.params['name'].split('.')[0])) # Remove all characters except alphanumeric and minus which is allowed by RFC 952 valid_hostname = re.sub(r"[^a-zA-Z0-9\-]", "", hostname) ident.hostName.name = valid_hostname # List of supported time zones for different vSphere versions in Linux/Unix systems # https://kb.vmware.com/s/article/2145518 if 'timezone' in self.params['customization']: ident.timeZone = str(self.params['customization']['timezone']) if 'hwclockUTC' in self.params['customization']: ident.hwClockUTC = self.params['customization']['hwclockUTC'] self.customspec = vim.vm.customization.Specification() self.customspec.nicSettingMap = adaptermaps self.customspec.globalIPSettings = globalip self.customspec.identity = ident def get_vm_scsi_controller(self, vm_obj): # If vm_obj doesn't exist there is no SCSI controller to find if vm_obj is None: return None for device in vm_obj.config.hardware.device: if self.device_helper.is_scsi_controller(device): scsi_ctl = vim.vm.device.VirtualDeviceSpec() scsi_ctl.device = device return scsi_ctl return None def get_configured_disk_size(self, expected_disk_spec): # what size is it? if [x for x in expected_disk_spec.keys() if x.startswith('size_') or x == 'size']: # size, size_tb, size_gb, size_mb, size_kb if 'size' in expected_disk_spec: size_regex = re.compile(r'(\d+(?:\.\d+)?)([tgmkTGMK][bB])') disk_size_m = size_regex.match(expected_disk_spec['size']) try: if disk_size_m: expected = disk_size_m.group(1) unit = disk_size_m.group(2) else: raise ValueError if re.match(r'\d+\.\d+', expected): # We found float value in string, let's typecast it expected = float(expected) else: # We found int value in string, let's typecast it expected = int(expected) if not expected or not unit: raise ValueError except (TypeError, ValueError, NameError): # Common failure self.module.fail_json(msg="Failed to parse disk size please review value" " provided using documentation.") else: param = [x for x in expected_disk_spec.keys() if x.startswith('size_')][0] unit = param.split('_')[-1].lower() expected = [x[1] for x in expected_disk_spec.items() if x[0].startswith('size_')][0] expected = int(expected) disk_units = dict(tb=3, gb=2, mb=1, kb=0) if unit in disk_units: unit = unit.lower() return expected * (1024 ** disk_units[unit]) else: self.module.fail_json(msg="%s is not a supported unit for disk size." " Supported units are ['%s']." % (unit, "', '".join(disk_units.keys()))) # No size found but disk, fail self.module.fail_json( msg="No size, size_kb, size_mb, size_gb or size_tb attribute found into disk configuration") def find_vmdk(self, vmdk_path): """ Takes a vsphere datastore path in the format [datastore_name] path/to/file.vmdk Returns vsphere file object or raises RuntimeError """ datastore_name, vmdk_fullpath, vmdk_filename, vmdk_folder = self.vmdk_disk_path_split(vmdk_path) datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name) if datastore is None: self.module.fail_json(msg="Failed to find the datastore %s" % datastore_name) return self.find_vmdk_file(datastore, vmdk_fullpath, vmdk_filename, vmdk_folder) def add_existing_vmdk(self, vm_obj, expected_disk_spec, diskspec, scsi_ctl): """ Adds vmdk file described by expected_disk_spec['filename'], retrieves the file information and adds the correct spec to self.configspec.deviceChange. """ filename = expected_disk_spec['filename'] # if this is a new disk, or the disk file names are different if (vm_obj and diskspec.device.backing.fileName != filename) or vm_obj is None: vmdk_file = self.find_vmdk(expected_disk_spec['filename']) diskspec.device.backing.fileName = expected_disk_spec['filename'] diskspec.device.capacityInKB = VmomiSupport.vmodlTypes['long'](vmdk_file.fileSize / 1024) diskspec.device.key = -1 self.change_detected = True self.configspec.deviceChange.append(diskspec) def configure_disks(self, vm_obj): # Ignore empty disk list, this permits to keep disks when deploying a template/cloning a VM if len(self.params['disk']) == 0: return scsi_ctl = self.get_vm_scsi_controller(vm_obj) # Create scsi controller only if we are deploying a new VM, not a template or reconfiguring if vm_obj is None or scsi_ctl is None: scsi_ctl = self.device_helper.create_scsi_controller(self.get_scsi_type()) self.change_detected = True self.configspec.deviceChange.append(scsi_ctl) disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)] \ if vm_obj is not None else None if disks is not None and self.params.get('disk') and len(self.params.get('disk')) < len(disks): self.module.fail_json(msg="Provided disks configuration has less disks than " "the target object (%d vs %d)" % (len(self.params.get('disk')), len(disks))) disk_index = 0 for expected_disk_spec in self.params.get('disk'): disk_modified = False # If we are manipulating and existing objects which has disks and disk_index is in disks if vm_obj is not None and disks is not None and disk_index < len(disks): diskspec = vim.vm.device.VirtualDeviceSpec() # set the operation to edit so that it knows to keep other settings diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit diskspec.device = disks[disk_index] else: diskspec = self.device_helper.create_scsi_disk(scsi_ctl, disk_index) disk_modified = True # increment index for next disk search disk_index += 1 # index 7 is reserved to SCSI controller if disk_index == 7: disk_index += 1 if 'disk_mode' in expected_disk_spec: disk_mode = expected_disk_spec.get('disk_mode', 'persistent').lower() valid_disk_mode = ['persistent', 'independent_persistent', 'independent_nonpersistent'] if disk_mode not in valid_disk_mode: self.module.fail_json(msg="disk_mode specified is not valid." " Should be one of ['%s']" % "', '".join(valid_disk_mode)) if (vm_obj and diskspec.device.backing.diskMode != disk_mode) or (vm_obj is None): diskspec.device.backing.diskMode = disk_mode disk_modified = True else: diskspec.device.backing.diskMode = "persistent" # is it thin? if 'type' in expected_disk_spec: disk_type = expected_disk_spec.get('type', '').lower() if disk_type == 'thin': diskspec.device.backing.thinProvisioned = True elif disk_type == 'eagerzeroedthick': diskspec.device.backing.eagerlyScrub = True if 'filename' in expected_disk_spec and expected_disk_spec['filename'] is not None: self.add_existing_vmdk(vm_obj, expected_disk_spec, diskspec, scsi_ctl) continue elif vm_obj is None or self.params['template']: # We are creating new VM or from Template # Only create virtual device if not backed by vmdk in original template if diskspec.device.backing.fileName == '': diskspec.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.create # which datastore? if expected_disk_spec.get('datastore'): # TODO: This is already handled by the relocation spec, # but it needs to eventually be handled for all the # other disks defined pass kb = self.get_configured_disk_size(expected_disk_spec) # VMware doesn't allow to reduce disk sizes if kb < diskspec.device.capacityInKB: self.module.fail_json( msg="Given disk size is smaller than found (%d < %d). Reducing disks is not allowed." % (kb, diskspec.device.capacityInKB)) if kb != diskspec.device.capacityInKB or disk_modified: diskspec.device.capacityInKB = kb self.configspec.deviceChange.append(diskspec) self.change_detected = True def select_host(self): hostsystem = self.cache.get_esx_host(self.params['esxi_hostname']) if not hostsystem: self.module.fail_json(msg='Failed to find ESX host "%(esxi_hostname)s"' % self.params) if hostsystem.runtime.connectionState != 'connected' or hostsystem.runtime.inMaintenanceMode: self.module.fail_json(msg='ESXi "%(esxi_hostname)s" is in invalid state or in maintenance mode.' % self.params) return hostsystem def autoselect_datastore(self): datastore = None datastores = self.cache.get_all_objs(self.content, [vim.Datastore]) if datastores is None or len(datastores) == 0: self.module.fail_json(msg="Unable to find a datastore list when autoselecting") datastore_freespace = 0 for ds in datastores: if not self.is_datastore_valid(datastore_obj=ds): continue if ds.summary.freeSpace > datastore_freespace: datastore = ds datastore_freespace = ds.summary.freeSpace return datastore def get_recommended_datastore(self, datastore_cluster_obj=None): """ Function to return Storage DRS recommended datastore from datastore cluster Args: datastore_cluster_obj: datastore cluster managed object Returns: Name of recommended datastore from the given datastore cluster """ if datastore_cluster_obj is None: return None # Check if Datastore Cluster provided by user is SDRS ready sdrs_status = datastore_cluster_obj.podStorageDrsEntry.storageDrsConfig.podConfig.enabled if sdrs_status: # We can get storage recommendation only if SDRS is enabled on given datastorage cluster pod_sel_spec = vim.storageDrs.PodSelectionSpec() pod_sel_spec.storagePod = datastore_cluster_obj storage_spec = vim.storageDrs.StoragePlacementSpec() storage_spec.podSelectionSpec = pod_sel_spec storage_spec.type = 'create' try: rec = self.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec) rec_action = rec.recommendations[0].action[0] return rec_action.destination.name except Exception: # There is some error so we fall back to general workflow pass datastore = None datastore_freespace = 0 for ds in datastore_cluster_obj.childEntity: if isinstance(ds, vim.Datastore) and ds.summary.freeSpace > datastore_freespace: # If datastore field is provided, filter destination datastores if not self.is_datastore_valid(datastore_obj=ds): continue datastore = ds datastore_freespace = ds.summary.freeSpace if datastore: return datastore.name return None def select_datastore(self, vm_obj=None): datastore = None datastore_name = None if len(self.params['disk']) != 0: # TODO: really use the datastore for newly created disks if 'autoselect_datastore' in self.params['disk'][0] and self.params['disk'][0]['autoselect_datastore']: datastores = self.cache.get_all_objs(self.content, [vim.Datastore]) datastores = [x for x in datastores if self.cache.get_parent_datacenter(x).name == self.params['datacenter']] if datastores is None or len(datastores) == 0: self.module.fail_json(msg="Unable to find a datastore list when autoselecting") datastore_freespace = 0 for ds in datastores: if not self.is_datastore_valid(datastore_obj=ds): continue if (ds.summary.freeSpace > datastore_freespace) or (ds.summary.freeSpace == datastore_freespace and not datastore): # If datastore field is provided, filter destination datastores if 'datastore' in self.params['disk'][0] and \ isinstance(self.params['disk'][0]['datastore'], str) and \ ds.name.find(self.params['disk'][0]['datastore']) < 0: continue datastore = ds datastore_name = datastore.name datastore_freespace = ds.summary.freeSpace elif 'datastore' in self.params['disk'][0]: datastore_name = self.params['disk'][0]['datastore'] # Check if user has provided datastore cluster first datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name) if datastore_cluster: # If user specified datastore cluster so get recommended datastore datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster) # Check if get_recommended_datastore or user specified datastore exists or not datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name) else: self.module.fail_json(msg="Either datastore or autoselect_datastore should be provided to select datastore") if not datastore and self.params['template']: # use the template's existing DS disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)] if disks: datastore = disks[0].backing.datastore datastore_name = datastore.name # validation if datastore: dc = self.cache.get_parent_datacenter(datastore) if dc.name != self.params['datacenter']: datastore = self.autoselect_datastore() datastore_name = datastore.name if not datastore: if len(self.params['disk']) != 0 or self.params['template'] is None: self.module.fail_json(msg="Unable to find the datastore with given parameters." " This could mean, %s is a non-existent virtual machine and module tried to" " deploy it as new virtual machine with no disk. Please specify disks parameter" " or specify template to clone from." % self.params['name']) self.module.fail_json(msg="Failed to find a matching datastore") return datastore, datastore_name def obj_has_parent(self, obj, parent): if obj is None and parent is None: raise AssertionError() current_parent = obj while True: if current_parent.name == parent.name: return True # Check if we have reached till root folder moid = current_parent._moId if moid in ['group-d1', 'ha-folder-root']: return False current_parent = current_parent.parent if current_parent is None: return False def get_scsi_type(self): disk_controller_type = "paravirtual" # set cpu/memory/etc if 'hardware' in self.params: if 'scsi' in self.params['hardware']: if self.params['hardware']['scsi'] in ['buslogic', 'paravirtual', 'lsilogic', 'lsilogicsas']: disk_controller_type = self.params['hardware']['scsi'] else: self.module.fail_json(msg="hardware.scsi attribute should be 'paravirtual' or 'lsilogic'") return disk_controller_type def find_folder(self, searchpath): """ Walk inventory objects one position of the searchpath at a time """ # split the searchpath so we can iterate through it paths = [x.replace('/', '') for x in searchpath.split('/')] paths_total = len(paths) - 1 position = 0 # recursive walk while looking for next element in searchpath root = self.content.rootFolder while root and position <= paths_total: change = False if hasattr(root, 'childEntity'): for child in root.childEntity: if child.name == paths[position]: root = child position += 1 change = True break elif isinstance(root, vim.Datacenter): if hasattr(root, 'vmFolder'): if root.vmFolder.name == paths[position]: root = root.vmFolder position += 1 change = True else: root = None if not change: root = None return root def get_resource_pool(self, cluster=None, host=None, resource_pool=None): """ Get a resource pool, filter on cluster, esxi_hostname or resource_pool if given """ cluster_name = cluster or self.params.get('cluster', None) host_name = host or self.params.get('esxi_hostname', None) resource_pool_name = resource_pool or self.params.get('resource_pool', None) # get the datacenter object datacenter = find_obj(self.content, [vim.Datacenter], self.params['datacenter']) if not datacenter: self.module.fail_json(msg='Unable to find datacenter "%s"' % self.params['datacenter']) # if cluster is given, get the cluster object if cluster_name: cluster = find_obj(self.content, [vim.ComputeResource], cluster_name, folder=datacenter) if not cluster: self.module.fail_json(msg='Unable to find cluster "%s"' % cluster_name) # if host is given, get the cluster object using the host elif host_name: host = find_obj(self.content, [vim.HostSystem], host_name, folder=datacenter) if not host: self.module.fail_json(msg='Unable to find host "%s"' % host_name) cluster = host.parent else: cluster = None # get resource pools limiting search to cluster or datacenter resource_pool = find_obj(self.content, [vim.ResourcePool], resource_pool_name, folder=cluster or datacenter) if not resource_pool: if resource_pool_name: self.module.fail_json(msg='Unable to find resource_pool "%s"' % resource_pool_name) else: self.module.fail_json(msg='Unable to find resource pool, need esxi_hostname, resource_pool, or cluster') return resource_pool def deploy_vm(self): # https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/clone_vm.py # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.CloneSpec.html # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.ConfigSpec.html # https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html # FIXME: # - static IPs self.folder = self.params.get('folder', None) if self.folder is None: self.module.fail_json(msg="Folder is required parameter while deploying new virtual machine") # Prepend / if it was missing from the folder path, also strip trailing slashes if not self.folder.startswith('/'): self.folder = '/%(folder)s' % self.params self.folder = self.folder.rstrip('/') datacenter = self.cache.find_obj(self.content, [vim.Datacenter], self.params['datacenter']) if datacenter is None: self.module.fail_json(msg='No datacenter named %(datacenter)s was found' % self.params) dcpath = compile_folder_path_for_object(datacenter) # Nested folder does not have trailing / if not dcpath.endswith('/'): dcpath += '/' # Check for full path first in case it was already supplied if (self.folder.startswith(dcpath + self.params['datacenter'] + '/vm') or self.folder.startswith(dcpath + '/' + self.params['datacenter'] + '/vm')): fullpath = self.folder elif self.folder.startswith('/vm/') or self.folder == '/vm': fullpath = "%s%s%s" % (dcpath, self.params['datacenter'], self.folder) elif self.folder.startswith('/'): fullpath = "%s%s/vm%s" % (dcpath, self.params['datacenter'], self.folder) else: fullpath = "%s%s/vm/%s" % (dcpath, self.params['datacenter'], self.folder) f_obj = self.content.searchIndex.FindByInventoryPath(fullpath) # abort if no strategy was successful if f_obj is None: # Add some debugging values in failure. details = { 'datacenter': datacenter.name, 'datacenter_path': dcpath, 'folder': self.folder, 'full_search_path': fullpath, } self.module.fail_json(msg='No folder %s matched in the search path : %s' % (self.folder, fullpath), details=details) destfolder = f_obj if self.params['template']: vm_obj = self.get_vm_or_template(template_name=self.params['template']) if vm_obj is None: self.module.fail_json(msg="Could not find a template named %(template)s" % self.params) else: vm_obj = None # always get a resource_pool resource_pool = self.get_resource_pool() # set the destination datastore for VM & disks if self.params['datastore']: # Give precedence to datastore value provided by user # User may want to deploy VM to specific datastore. datastore_name = self.params['datastore'] # Check if user has provided datastore cluster first datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name) if datastore_cluster: # If user specified datastore cluster so get recommended datastore datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster) # Check if get_recommended_datastore or user specified datastore exists or not datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name) else: (datastore, datastore_name) = self.select_datastore(vm_obj) self.configspec = vim.vm.ConfigSpec() self.configspec.deviceChange = [] # create the relocation spec self.relospec = vim.vm.RelocateSpec() self.relospec.deviceChange = [] self.configure_guestid(vm_obj=vm_obj, vm_creation=True) self.configure_cpu_and_memory(vm_obj=vm_obj, vm_creation=True) self.configure_hardware_params(vm_obj=vm_obj) self.configure_resource_alloc_info(vm_obj=vm_obj) self.configure_vapp_properties(vm_obj=vm_obj) self.configure_disks(vm_obj=vm_obj) self.configure_network(vm_obj=vm_obj) self.configure_cdrom(vm_obj=vm_obj) # Find if we need network customizations (find keys in dictionary that requires customizations) network_changes = False for nw in self.params['networks']: for key in nw: # We don't need customizations for these keys if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected'): network_changes = True break if len(self.params['customization']) > 0 or network_changes or self.params.get('customization_spec') is not None: self.customize_vm(vm_obj=vm_obj) clonespec = None clone_method = None try: if self.params['template']: # Only select specific host when ESXi hostname is provided if self.params['esxi_hostname']: self.relospec.host = self.select_host() self.relospec.datastore = datastore # Convert disk present in template if is set if self.params['convert']: for device in vm_obj.config.hardware.device: if isinstance(device, vim.vm.device.VirtualDisk): disk_locator = vim.vm.RelocateSpec.DiskLocator() disk_locator.diskBackingInfo = vim.vm.device.VirtualDisk.FlatVer2BackingInfo() if self.params['convert'] in ['thin']: disk_locator.diskBackingInfo.thinProvisioned = True if self.params['convert'] in ['eagerzeroedthick']: disk_locator.diskBackingInfo.eagerlyScrub = True if self.params['convert'] in ['thick']: disk_locator.diskBackingInfo.diskMode = "persistent" disk_locator.diskId = device.key disk_locator.datastore = datastore self.relospec.disk.append(disk_locator) # https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html # > pool: For a clone operation from a template to a virtual machine, this argument is required. self.relospec.pool = resource_pool linked_clone = self.params.get('linked_clone') snapshot_src = self.params.get('snapshot_src', None) if linked_clone: if snapshot_src is not None: self.relospec.diskMoveType = vim.vm.RelocateSpec.DiskMoveOptions.createNewChildDiskBacking else: self.module.fail_json(msg="Parameter 'linked_src' and 'snapshot_src' are" " required together for linked clone operation.") clonespec = vim.vm.CloneSpec(template=self.params['is_template'], location=self.relospec) if self.customspec: clonespec.customization = self.customspec if snapshot_src is not None: if vm_obj.snapshot is None: self.module.fail_json(msg="No snapshots present for virtual machine or template [%(template)s]" % self.params) snapshot = self.get_snapshots_by_name_recursively(snapshots=vm_obj.snapshot.rootSnapshotList, snapname=snapshot_src) if len(snapshot) != 1: self.module.fail_json(msg='virtual machine "%(template)s" does not contain' ' snapshot named "%(snapshot_src)s"' % self.params) clonespec.snapshot = snapshot[0].snapshot clonespec.config = self.configspec clone_method = 'Clone' try: task = vm_obj.Clone(folder=destfolder, name=self.params['name'], spec=clonespec) except vim.fault.NoPermission as e: self.module.fail_json(msg="Failed to clone virtual machine %s to folder %s " "due to permission issue: %s" % (self.params['name'], destfolder, to_native(e.msg))) self.change_detected = True else: # ConfigSpec require name for VM creation self.configspec.name = self.params['name'] self.configspec.files = vim.vm.FileInfo(logDirectory=None, snapshotDirectory=None, suspendDirectory=None, vmPathName="[" + datastore_name + "]") clone_method = 'CreateVM_Task' try: task = destfolder.CreateVM_Task(config=self.configspec, pool=resource_pool) except vmodl.fault.InvalidRequest as e: self.module.fail_json(msg="Failed to create virtual machine due to invalid configuration " "parameter %s" % to_native(e.msg)) except vim.fault.RestrictedVersion as e: self.module.fail_json(msg="Failed to create virtual machine due to " "product versioning restrictions: %s" % to_native(e.msg)) self.change_detected = True self.wait_for_task(task) except TypeError as e: self.module.fail_json(msg="TypeError was returned, please ensure to give correct inputs. %s" % to_text(e)) if task.info.state == 'error': # https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2021361 # https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2173 # provide these to the user for debugging clonespec_json = serialize_spec(clonespec) configspec_json = serialize_spec(self.configspec) kwargs = { 'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'clonespec': clonespec_json, 'configspec': configspec_json, 'clone_method': clone_method } return kwargs else: # set annotation vm = task.info.result if self.params['annotation']: annotation_spec = vim.vm.ConfigSpec() annotation_spec.annotation = str(self.params['annotation']) task = vm.ReconfigVM_Task(annotation_spec) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'annotation'} if self.params['customvalues']: self.customize_customvalues(vm_obj=vm) if self.params['wait_for_ip_address'] or self.params['wait_for_customization'] or self.params['state'] in ['poweredon', 'restarted']: set_vm_power_state(self.content, vm, 'poweredon', force=False) if self.params['wait_for_ip_address']: wait_for_vm_ip(self.content, vm, self.params['wait_for_ip_address_timeout']) if self.params['wait_for_customization']: is_customization_ok = self.wait_for_customization(vm) if not is_customization_ok: vm_facts = self.gather_facts(vm) return {'changed': self.change_applied, 'failed': True, 'instance': vm_facts, 'op': 'customization'} vm_facts = self.gather_facts(vm) return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts} def get_snapshots_by_name_recursively(self, snapshots, snapname): snap_obj = [] for snapshot in snapshots: if snapshot.name == snapname: snap_obj.append(snapshot) else: snap_obj = snap_obj + self.get_snapshots_by_name_recursively(snapshot.childSnapshotList, snapname) return snap_obj def reconfigure_vm(self): self.configspec = vim.vm.ConfigSpec() self.configspec.deviceChange = [] # create the relocation spec self.relospec = vim.vm.RelocateSpec() self.relospec.deviceChange = [] self.configure_guestid(vm_obj=self.current_vm_obj) self.configure_cpu_and_memory(vm_obj=self.current_vm_obj) self.configure_hardware_params(vm_obj=self.current_vm_obj) self.configure_disks(vm_obj=self.current_vm_obj) self.configure_network(vm_obj=self.current_vm_obj) self.configure_cdrom(vm_obj=self.current_vm_obj) self.customize_customvalues(vm_obj=self.current_vm_obj) self.configure_resource_alloc_info(vm_obj=self.current_vm_obj) self.configure_vapp_properties(vm_obj=self.current_vm_obj) if self.params['annotation'] and self.current_vm_obj.config.annotation != self.params['annotation']: self.configspec.annotation = str(self.params['annotation']) self.change_detected = True if self.params['resource_pool']: self.relospec.pool = self.get_resource_pool() if self.relospec.pool != self.current_vm_obj.resourcePool: task = self.current_vm_obj.RelocateVM_Task(spec=self.relospec) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'relocate'} # Only send VMware task if we see a modification if self.change_detected: task = None try: task = self.current_vm_obj.ReconfigVM_Task(spec=self.configspec) except vim.fault.RestrictedVersion as e: self.module.fail_json(msg="Failed to reconfigure virtual machine due to" " product versioning restrictions: %s" % to_native(e.msg)) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'reconfig'} # Rename VM if self.params['uuid'] and self.params['name'] and self.params['name'] != self.current_vm_obj.config.name: task = self.current_vm_obj.Rename_Task(self.params['name']) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'rename'} # Mark VM as Template if self.params['is_template'] and not self.current_vm_obj.config.template: try: self.current_vm_obj.MarkAsTemplate() self.change_applied = True except vmodl.fault.NotSupported as e: self.module.fail_json(msg="Failed to mark virtual machine [%s] " "as template: %s" % (self.params['name'], e.msg)) # Mark Template as VM elif not self.params['is_template'] and self.current_vm_obj.config.template: resource_pool = self.get_resource_pool() kwargs = dict(pool=resource_pool) if self.params.get('esxi_hostname', None): host_system_obj = self.select_host() kwargs.update(host=host_system_obj) try: self.current_vm_obj.MarkAsVirtualMachine(**kwargs) self.change_applied = True except vim.fault.InvalidState as invalid_state: self.module.fail_json(msg="Virtual machine is not marked" " as template : %s" % to_native(invalid_state.msg)) except vim.fault.InvalidDatastore as invalid_ds: self.module.fail_json(msg="Converting template to virtual machine" " operation cannot be performed on the" " target datastores: %s" % to_native(invalid_ds.msg)) except vim.fault.CannotAccessVmComponent as cannot_access: self.module.fail_json(msg="Failed to convert template to virtual machine" " as operation unable access virtual machine" " component: %s" % to_native(cannot_access.msg)) except vmodl.fault.InvalidArgument as invalid_argument: self.module.fail_json(msg="Failed to convert template to virtual machine" " due to : %s" % to_native(invalid_argument.msg)) except Exception as generic_exc: self.module.fail_json(msg="Failed to convert template to virtual machine" " due to generic error : %s" % to_native(generic_exc)) # Automatically update VMware UUID when converting template to VM. # This avoids an interactive prompt during VM startup. uuid_action = [x for x in self.current_vm_obj.config.extraConfig if x.key == "uuid.action"] if not uuid_action: uuid_action_opt = vim.option.OptionValue() uuid_action_opt.key = "uuid.action" uuid_action_opt.value = "create" self.configspec.extraConfig.append(uuid_action_opt) self.change_detected = True # add customize existing VM after VM re-configure if 'existing_vm' in self.params['customization'] and self.params['customization']['existing_vm']: if self.current_vm_obj.config.template: self.module.fail_json(msg="VM is template, not support guest OS customization.") if self.current_vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOff: self.module.fail_json(msg="VM is not in poweroff state, can not do guest OS customization.") cus_result = self.customize_exist_vm() if cus_result['failed']: return cus_result vm_facts = self.gather_facts(self.current_vm_obj) return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts} def customize_exist_vm(self): task = None # Find if we need network customizations (find keys in dictionary that requires customizations) network_changes = False for nw in self.params['networks']: for key in nw: # We don't need customizations for these keys if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected'): network_changes = True break if len(self.params['customization']) > 1 or network_changes or self.params.get('customization_spec'): self.customize_vm(vm_obj=self.current_vm_obj) try: task = self.current_vm_obj.CustomizeVM_Task(self.customspec) except vim.fault.CustomizationFault as e: self.module.fail_json(msg="Failed to customization virtual machine due to CustomizationFault: %s" % to_native(e.msg)) except vim.fault.RuntimeFault as e: self.module.fail_json(msg="failed to customization virtual machine due to RuntimeFault: %s" % to_native(e.msg)) except Exception as e: self.module.fail_json(msg="failed to customization virtual machine due to fault: %s" % to_native(e.msg)) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'customize_exist'} if self.params['wait_for_customization']: set_vm_power_state(self.content, self.current_vm_obj, 'poweredon', force=False) is_customization_ok = self.wait_for_customization(self.current_vm_obj) if not is_customization_ok: return {'changed': self.change_applied, 'failed': True, 'op': 'wait_for_customize_exist'} return {'changed': self.change_applied, 'failed': False} def wait_for_task(self, task, poll_interval=1): """ Wait for a VMware task to complete. Terminal states are 'error' and 'success'. Inputs: - task: the task to wait for - poll_interval: polling interval to check the task, in seconds Modifies: - self.change_applied """ # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.Task.html # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.TaskInfo.html # https://github.com/virtdevninja/pyvmomi-community-samples/blob/master/samples/tools/tasks.py while task.info.state not in ['error', 'success']: time.sleep(poll_interval) self.change_applied = self.change_applied or task.info.state == 'success' def get_vm_events(self, vm, eventTypeIdList): byEntity = vim.event.EventFilterSpec.ByEntity(entity=vm, recursion="self") filterSpec = vim.event.EventFilterSpec(entity=byEntity, eventTypeId=eventTypeIdList) eventManager = self.content.eventManager return eventManager.QueryEvent(filterSpec) def wait_for_customization(self, vm, poll=10000, sleep=10): thispoll = 0 while thispoll <= poll: eventStarted = self.get_vm_events(vm, ['CustomizationStartedEvent']) if len(eventStarted): thispoll = 0 while thispoll <= poll: eventsFinishedResult = self.get_vm_events(vm, ['CustomizationSucceeded', 'CustomizationFailed']) if len(eventsFinishedResult): if not isinstance(eventsFinishedResult[0], vim.event.CustomizationSucceeded): self.module.fail_json(msg='Customization failed with error {0}:\n{1}'.format( eventsFinishedResult[0]._wsdlName, eventsFinishedResult[0].fullFormattedMessage)) return False break else: time.sleep(sleep) thispoll += 1 return True else: time.sleep(sleep) thispoll += 1 self.module.fail_json('waiting for customizations timed out.') return False def main(): argument_spec = vmware_argument_spec() argument_spec.update( state=dict(type='str', default='present', choices=['absent', 'poweredoff', 'poweredon', 'present', 'rebootguest', 'restarted', 'shutdownguest', 'suspended']), template=dict(type='str', aliases=['template_src']), is_template=dict(type='bool', default=False), annotation=dict(type='str', aliases=['notes']), customvalues=dict(type='list', default=[]), name=dict(type='str'), name_match=dict(type='str', choices=['first', 'last'], default='first'), uuid=dict(type='str'), use_instance_uuid=dict(type='bool', default=False), folder=dict(type='str'), guest_id=dict(type='str'), disk=dict(type='list', default=[]), cdrom=dict(type=list_or_dict, default=[]), hardware=dict(type='dict', default={}), force=dict(type='bool', default=False), datacenter=dict(type='str', default='ha-datacenter'), esxi_hostname=dict(type='str'), cluster=dict(type='str'), wait_for_ip_address=dict(type='bool', default=False), wait_for_ip_address_timeout=dict(type='int', default=300), state_change_timeout=dict(type='int', default=0), snapshot_src=dict(type='str'), linked_clone=dict(type='bool', default=False), networks=dict(type='list', default=[]), resource_pool=dict(type='str'), customization=dict(type='dict', default={}, no_log=True), customization_spec=dict(type='str', default=None), wait_for_customization=dict(type='bool', default=False), vapp_properties=dict(type='list', default=[]), datastore=dict(type='str'), convert=dict(type='str', choices=['thin', 'thick', 'eagerzeroedthick']), delete_from_inventory=dict(type='bool', default=False), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[ ['cluster', 'esxi_hostname'], ], required_one_of=[ ['name', 'uuid'], ], ) result = {'failed': False, 'changed': False} pyv = PyVmomiHelper(module) # Check if the VM exists before continuing vm = pyv.get_vm() # VM already exists if vm: if module.params['state'] == 'absent': # destroy it if module.check_mode: result.update( vm_name=vm.name, changed=True, current_powerstate=vm.summary.runtime.powerState.lower(), desired_operation='remove_vm', ) module.exit_json(**result) if module.params['force']: # has to be poweredoff first set_vm_power_state(pyv.content, vm, 'poweredoff', module.params['force']) result = pyv.remove_vm(vm, module.params['delete_from_inventory']) elif module.params['state'] == 'present': if module.check_mode: result.update( vm_name=vm.name, changed=True, desired_operation='reconfigure_vm', ) module.exit_json(**result) result = pyv.reconfigure_vm() elif module.params['state'] in ['poweredon', 'poweredoff', 'restarted', 'suspended', 'shutdownguest', 'rebootguest']: if module.check_mode: result.update( vm_name=vm.name, changed=True, current_powerstate=vm.summary.runtime.powerState.lower(), desired_operation='set_vm_power_state', ) module.exit_json(**result) # set powerstate tmp_result = set_vm_power_state(pyv.content, vm, module.params['state'], module.params['force'], module.params['state_change_timeout']) if tmp_result['changed']: result["changed"] = True if module.params['state'] in ['poweredon', 'restarted', 'rebootguest'] and module.params['wait_for_ip_address']: wait_result = wait_for_vm_ip(pyv.content, vm, module.params['wait_for_ip_address_timeout']) if not wait_result: module.fail_json(msg='Waiting for IP address timed out') tmp_result['instance'] = wait_result if not tmp_result["failed"]: result["failed"] = False result['instance'] = tmp_result['instance'] if tmp_result["failed"]: result["failed"] = True result["msg"] = tmp_result["msg"] else: # This should not happen raise AssertionError() # VM doesn't exist else: if module.params['state'] in ['poweredon', 'poweredoff', 'present', 'restarted', 'suspended']: if module.check_mode: result.update( changed=True, desired_operation='deploy_vm', ) module.exit_json(**result) result = pyv.deploy_vm() if result['failed']: module.fail_json(msg='Failed to create a virtual machine : %s' % result['msg']) if result['failed']: module.fail_json(**result) else: module.exit_json(**result) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
63,761
ios_interfaces: non-existing virtual/loopback interfaces not getting confiured
##### SUMMARY ios_interfaces module is not confguring non-existing loopback and virtual interfaces . This is observed for state='merged','overridden','replaced' ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME ios_interfaces.py ##### ANSIBLE VERSION ``` ansible 2.10.0.dev0 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/gosriniv/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/gosriniv/ansible/lib/ansible executable location = /home/gosriniv/ansible/bin/ansible python version = 3.6.5 (default, Sep 4 2019, 12:23:33) [GCC 9.0.1 20190312 (Red Hat 9.0.1-0.10)] ``` ##### OS / ENVIRONMENT ios ##### STEPS TO REPRODUCE ```tasks: - name: Merge given interface attributes with device configuration ios_interfaces: config: - name: loopback200 description: 'Configured by Ansible' enabled: True state: merged ``` ##### EXPECTED RESULTS The loopback interface should be configured in the device ##### ACTUAL RESULTS ok: [10.8.38.75] => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "before": [ { "enabled": true, "name": "loopback100" }, { "enabled": true, "name": "Port-channel10" }, { "enabled": true, "name": "Port-channel40" }, { "enabled": true, "name": "GigabitEthernet0/0" }, { "enabled": true, "name": "GigabitEthernet0/1" }, { "enabled": true, "name": "GigabitEthernet0/2" } ], "changed": false, "commands": [], "invocation": { "module_args": { "config": [ { "description": "Configured by Ansible", "duplex": null, "enabled": true, "mtu": null, "name": "loopback200", "speed": null } ], "state": "merged" } } }
https://github.com/ansible/ansible/issues/63761
https://github.com/ansible/ansible/pull/63901
548fa65ac6db1f3b24944a106fa01872362fea17
be1bcc745019613c722c73c1562c11215b146dd3
2019-10-21T18:34:08Z
python
2019-10-31T12:39:03Z
lib/ansible/module_utils/network/ios/config/interfaces/interfaces.py
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The ios_interfaces class It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessary to bring the current configuration to it's desired end-state is created """ from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.module_utils.network.common.cfg.base import ConfigBase from ansible.module_utils.network.common.utils import to_list from ansible.module_utils.network.ios.facts.facts import Facts from ansible.module_utils.network.ios.utils.utils import get_interface_type, dict_to_set from ansible.module_utils.network.ios.utils.utils import remove_command_from_config_list, add_command_to_config_list from ansible.module_utils.network.ios.utils.utils import filter_dict_having_none_value, remove_duplicate_interface class Interfaces(ConfigBase): """ The ios_interfaces class """ gather_subset = [ '!all', '!min', ] gather_network_resources = [ 'interfaces', ] params = ('description', 'mtu', 'speed', 'duplex') def __init__(self, module): super(Interfaces, self).__init__(module) def get_interfaces_facts(self): """ Get the 'facts' (the current configuration) :rtype: A dictionary :returns: The current configuration as a dictionary """ facts, _warnings = Facts(self._module).get_facts(self.gather_subset, self.gather_network_resources) interfaces_facts = facts['ansible_network_resources'].get('interfaces') if not interfaces_facts: return [] return interfaces_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from moduel execution """ result = {'changed': False} commands = list() warnings = list() existing_interfaces_facts = self.get_interfaces_facts() commands.extend(self.set_config(existing_interfaces_facts)) if commands: if not self._module.check_mode: self._connection.edit_config(commands) result['changed'] = True result['commands'] = commands changed_interfaces_facts = self.get_interfaces_facts() result['before'] = existing_interfaces_facts if result['changed']: result['after'] = changed_interfaces_facts result['warnings'] = warnings return result def set_config(self, existing_interfaces_facts): """ Collect the configuration from the args passed to the module, collect the current configuration (as a dict from facts) :rtype: A list :returns: the commands necessary to migrate the current configuration to the deisred configuration """ want = self._module.params['config'] have = existing_interfaces_facts resp = self.set_state(want, have) return to_list(resp) def set_state(self, want, have): """ Select the appropriate function based on the state provided :param want: the desired configuration as a dictionary :param have: the current configuration as a dictionary :rtype: A list :returns: the commands necessary to migrate the current configuration to the deisred configuration """ commands = [] state = self._module.params['state'] if state in ('overridden', 'merged', 'replaced') and not want: self._module.fail_json(msg='value of config parameter must not be empty for state {0}'.format(state)) if state == 'overridden': commands = self._state_overridden(want, have) elif state == 'deleted': commands = self._state_deleted(want, have) elif state == 'merged': commands = self._state_merged(want, have) elif state == 'replaced': commands = self._state_replaced(want, have) return commands def _state_replaced(self, want, have): """ The command generator when state is replaced :param want: the desired configuration as a dictionary :param have: the current configuration as a dictionary :param interface_type: interface type :rtype: A list :returns: the commands necessary to migrate the current configuration to the deisred configuration """ commands = [] for interface in want: for each in have: if each['name'] == interface['name']: break elif interface['name'] in each['name']: break else: continue have_dict = filter_dict_having_none_value(interface, each) want = dict() commands.extend(self._clear_config(want, have_dict)) commands.extend(self._set_config(interface, each)) # Remove the duplicate interface call commands = remove_duplicate_interface(commands) return commands def _state_overridden(self, want, have): """ The command generator when state is overridden :param want: the desired configuration as a dictionary :param obj_in_have: the current configuration as a dictionary :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ commands = [] for each in have: for interface in want: if each['name'] == interface['name']: break elif interface['name'] in each['name']: break else: # We didn't find a matching desired state, which means we can # pretend we recieved an empty desired state. interface = dict(name=each['name']) commands.extend(self._clear_config(interface, each)) continue have_dict = filter_dict_having_none_value(interface, each) want = dict() commands.extend(self._clear_config(want, have_dict)) commands.extend(self._set_config(interface, each)) # Remove the duplicate interface call commands = remove_duplicate_interface(commands) return commands def _state_merged(self, want, have): """ The command generator when state is merged :param want: the additive configuration as a dictionary :param obj_in_have: the current configuration as a dictionary :rtype: A list :returns: the commands necessary to merge the provided into the current configuration """ commands = [] for interface in want: for each in have: if each['name'] == interface['name']: break else: continue commands.extend(self._set_config(interface, each)) return commands def _state_deleted(self, want, have): """ The command generator when state is deleted :param want: the objects from which the configuration should be removed :param obj_in_have: the current configuration as a dictionary :param interface_type: interface type :rtype: A list :returns: the commands necessary to remove the current configuration of the provided objects """ commands = [] if want: for interface in want: for each in have: if each['name'] == interface['name']: break else: continue interface = dict(name=interface['name']) commands.extend(self._clear_config(interface, each)) else: for each in have: want = dict() commands.extend(self._clear_config(want, each)) return commands def _set_config(self, want, have): # Set the interface config based on the want and have config commands = [] interface = 'interface ' + want['name'] # Get the diff b/w want and have want_dict = dict_to_set(want) have_dict = dict_to_set(have) diff = want_dict - have_dict if diff: diff = dict(diff) for item in self.params: if diff.get(item): cmd = item + ' ' + str(want.get(item)) add_command_to_config_list(interface, cmd, commands) if diff.get('enabled'): add_command_to_config_list(interface, 'no shutdown', commands) elif diff.get('enabled') is False: add_command_to_config_list(interface, 'shutdown', commands) return commands def _clear_config(self, want, have): # Delete the interface config based on the want and have config commands = [] if want.get('name'): interface_type = get_interface_type(want['name']) interface = 'interface ' + want['name'] else: interface_type = get_interface_type(have['name']) interface = 'interface ' + have['name'] if have.get('description') and want.get('description') != have.get('description'): remove_command_from_config_list(interface, 'description', commands) if not have.get('enabled') and want.get('enabled') != have.get('enabled'): # if enable is False set enable as True which is the default behavior remove_command_from_config_list(interface, 'shutdown', commands) if interface_type.lower() == 'gigabitethernet': if have.get('speed') and have.get('speed') != 'auto' and want.get('speed') != have.get('speed'): remove_command_from_config_list(interface, 'speed', commands) if have.get('duplex') and have.get('duplex') != 'auto' and want.get('duplex') != have.get('duplex'): remove_command_from_config_list(interface, 'duplex', commands) if have.get('mtu') and want.get('mtu') != have.get('mtu'): remove_command_from_config_list(interface, 'mtu', commands) return commands
closed
ansible/ansible
https://github.com/ansible/ansible
60,111
redfish_config can't set boot order on Huawei server (multiple attributes required)
##### SUMMARY Trying to set the boot order on a Huawei 2288H V5 via iBMC/redfish, redfish_config module fails because it needs to set the 4 `BootTypeOrderX` at the same time, and we currently only have the option to set 1 at a time This report is in between `Bug Report` and `Feature Idea` ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME redfish_config ##### ANSIBLE VERSION ``` ansible 2.9.0.dev0 config file = /home/echampetier/git/ops/provisioning/ansible.cfg configured module search path = [u'/home/echampetier/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /usr/bin/ansible python version = 2.7.16 (default, Apr 30 2019, 15:54:43) [GCC 9.0.1 20190312 (Red Hat 9.0.1-0.10)] ``` ##### CONFIGURATION ``` ANSIBLE_PIPELINING(/home/echampetier/git/ops/provisioning/ansible.cfg) = True DEFAULT_CALLBACK_WHITELIST(/home/echampetier/git/ops/provisioning/ansible.cfg) = [u'profile_tasks'] DEFAULT_REMOTE_USER(/home/echampetier/git/ops/provisioning/ansible.cfg) = root ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Fedora 30 Huawei 2288H V5 with iBMC 3.55 (U4282) ##### STEPS TO REPRODUCE ```yaml - name: Set Bios config redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: "BootTypeOrder0" bios_attribute_value: "Others" baseuri: "{{ ibmc_ip }}" username: "{{ ibmc_user }}" password: "{{ ibmc_pass }}" delegate_to: localhost ``` ##### EXPECTED RESULTS It works ! ##### ACTUAL RESULTS ``` Using module file /usr/lib/python2.7/site-packages/ansible/modules/remote_management/redfish/redfish_config.py Pipelining is enabled. <localhost> ESTABLISH LOCAL CONNECTION FOR USER: echampetier <localhost> EXEC /bin/sh -c '/usr/bin/python2 && sleep 0' fatal: [192.168.1.3 -> localhost]: FAILED! => { "changed": false, "invocation": { "module_args": { "baseuri": "192.168.1.2", "bios_attribute_name": "BootTypeOrder0", "bios_attribute_value": "Others", "category": "Systems", "command": [ "SetBiosAttributes" ], "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "timeout": 10, "username": "Administrator" } }, "msg": "HTTP Error 400 on PATCH request to 'https://192.168.1.2/redfish/v1/Systems/1/Bios/Settings', extended message: 'Failed to set the BIOS boot order.'" } ``` When using curl: ``` $ curl -u 'Administrator:<redacted>' -XPATCH https://192.168.1.2/redfish/v1/Systems/1/Bios/Settings -d '{"Attributes": {"BootTypeOrder0": "Others"}}' -k -vvv -H 'Content-Type: application/json' -H 'If-Match: W/"6168147f"' -s | jq . ... < HTTP/1.1 400 Bad Request < Date: Mon, 05 Aug 2019 21:31:18 GMT < X-Frame-Options: SAMEORIGIN < X-Download-Options: noopen < Content-Security-Policy: default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self' wss://*:*; img-src 'self' data:; frame-src 'self'; font-src 'self'; object-src 'self'; style-src 'self' 'unsafe-inline' < OData-Version: 4.0 < Cache-Control: max-age=0, no-cache, no-store, must-revalidate < Content-Length: 535 < X-XSS-Protection: 1; mode=block < Strict-Transport-Security: max-age=31536000; includeSubDomains < X-Content-Type-Options: nosniff < Expires: 0 < Connection: close < Content-Type: application/json;charset=utf-8 { "error": { "code": "Base.1.0.GeneralError", "message": "A general error has occurred. See ExtendedInfo for more information.", "@Message.ExtendedInfo": [ { "@odata.type": "/redfish/v1/$metadata#MessageRegistry.1.0.0.MessageRegistry", "MessageId": "iBMC.1.0.SettingBootOrderFailed", "RelatedProperties": [], "Message": "Failed to set the BIOS boot order.", "MessageArgs": [], "Severity": "Warning", "Resolution": "Check that the four property names are correct, all the four properties are set, and the property values are different from each other." } ] } } ``` And when sending the 4 at the same time it works ``` $ curl -u 'Administrator:<redacted>' -XPATCH https://192.168.1.2/redfish/v1/Systems/1/Bios/Settings -d '{"Attributes": {"BootTypeOrder0":"Others", "BootTypeOrder1":"HardDiskDrive", "BootTypeOrder2":"DVDROMDrive", "BootTypeOrder3":"PXE"}}' -k -vvv -H 'Content-Type: application/json' -H 'If-Match: W/"6168147f"' -s | jq . ... < HTTP/1.1 200 OK < Date: Mon, 05 Aug 2019 21:34:08 GMT < X-Frame-Options: SAMEORIGIN < X-Download-Options: noopen < Content-Security-Policy: default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self' wss://*:*; img-src 'self' data:; frame-src 'self'; font-src 'self'; object-src 'self'; style-src 'self' 'unsafe-inline' < OData-Version: 4.0 < Cache-Control: max-age=0, no-cache, no-store, must-revalidate < ETag: W/"7d41337e" < Content-Length: 705 < X-XSS-Protection: 1; mode=block < Strict-Transport-Security: max-age=31536000; includeSubDomains < X-Content-Type-Options: nosniff < Expires: 0 < Content-Type: application/json;charset=utf-8 < { "@odata.context": "/redfish/v1/$metadata#Systems/Members/1/Bios/Settings/$entity", "@odata.id": "/redfish/v1/Systems/1/Bios/Settings", "@odata.type": "#Bios.v1_0_0.Bios", "Id": "Settings", "Name": "BIOS Configuration Pending Settings", "AttributeRegistry": "BiosAttributeRegistry.1.9.9", "Attributes": { "BootTypeOrder0": "Others", "BootTypeOrder1": "HardDiskDrive", "BootTypeOrder2": "DVDROMDrive", "BootTypeOrder3": "PXE" }, "Actions": { "Oem": { "Huawei": { "#Settings.Revoke": { "target": "/redfish/v1/Systems/1/Bios/Settings/Actions/Oem/Huawei/Settings.Revoke", "@Redfish.ActionInfo": "/redfish/v1/Systems/1/Bios/Settings/SettingsRevokeActionInfo" } } } } } ```
https://github.com/ansible/ansible/issues/60111
https://github.com/ansible/ansible/pull/62764
ec1c5585af424f4c43fa7a16cbf82c2571045415
b4cd9086dca54ae2865d6c54917924959ecf9eb8
2019-08-05T21:43:24Z
python
2019-10-31T14:47:05Z
lib/ansible/module_utils/redfish_utils.py
# Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import json from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import http_client from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} class RedfishUtils(object): def __init__(self, creds, root_uri, timeout, module): self.root_uri = root_uri self.creds = creds self.timeout = timeout self.module = module self.service_root = '/redfish/v1/' self._init_session() # The following functions are to send GET/POST/PATCH/DELETE requests def get_request(self, uri): try: resp = open_url(uri, method="GET", headers=GET_HEADERS, url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) data = json.loads(resp.read()) headers = dict((k.lower(), v) for (k, v) in resp.info().items()) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'data': data, 'headers': headers} def post_request(self, uri, pyld): try: resp = open_url(uri, data=json.dumps(pyld), headers=POST_HEADERS, method="POST", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def patch_request(self, uri, pyld): headers = PATCH_HEADERS r = self.get_request(uri) if r['ret']: # Get etag from etag header or @odata.etag property etag = r['headers'].get('etag') if not etag: etag = r['data'].get('@odata.etag') if etag: # Make copy of headers and add If-Match header headers = dict(headers) headers['If-Match'] = etag try: resp = open_url(uri, data=json.dumps(pyld), headers=headers, method="PATCH", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def delete_request(self, uri, pyld=None): try: data = json.dumps(pyld) if pyld else None resp = open_url(uri, data=data, headers=DELETE_HEADERS, method="DELETE", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} @staticmethod def _get_extended_message(error): """ Get Redfish ExtendedInfo message from response payload if present :param error: an HTTPError exception :type error: HTTPError :return: the ExtendedInfo message if present, else standard HTTP error """ msg = http_client.responses.get(error.code, '') if error.code >= 400: try: body = error.read().decode('utf-8') data = json.loads(body) ext_info = data['error']['@Message.ExtendedInfo'] msg = ext_info[0]['Message'] except Exception: pass return msg def _init_session(self): pass def _find_accountservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} else: account_service = data["AccountService"]["@odata.id"] response = self.get_request(self.root_uri + account_service) if response['ret'] is False: return response data = response['data'] accounts = data['Accounts']['@odata.id'] if accounts[-1:] == '/': accounts = accounts[:-1] self.accounts_uri = accounts return {'ret': True} def _find_sessionservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'SessionService' not in data: return {'ret': False, 'msg': "SessionService resource not found"} else: session_service = data["SessionService"]["@odata.id"] response = self.get_request(self.root_uri + session_service) if response['ret'] is False: return response data = response['data'] sessions = data['Sessions']['@odata.id'] if sessions[-1:] == '/': sessions = sessions[:-1] self.sessions_uri = sessions return {'ret': True} def _find_systems_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Systems' not in data: return {'ret': False, 'msg': "Systems resource not found"} response = self.get_request(self.root_uri + data['Systems']['@odata.id']) if response['ret'] is False: return response self.systems_uris = [ i['@odata.id'] for i in response['data'].get('Members', [])] if not self.systems_uris: return { 'ret': False, 'msg': "ComputerSystem's Members array is either empty or missing"} return {'ret': True} def _find_updateservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'UpdateService' not in data: return {'ret': False, 'msg': "UpdateService resource not found"} else: update = data["UpdateService"]["@odata.id"] self.update_uri = update response = self.get_request(self.root_uri + update) if response['ret'] is False: return response data = response['data'] self.firmware_uri = self.software_uri = None if 'FirmwareInventory' in data: self.firmware_uri = data['FirmwareInventory'][u'@odata.id'] if 'SoftwareInventory' in data: self.software_uri = data['SoftwareInventory'][u'@odata.id'] return {'ret': True} def _find_chassis_resource(self): chassis_service = [] response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Chassis' not in data: return {'ret': False, 'msg': "Chassis resource not found"} else: chassis = data["Chassis"]["@odata.id"] response = self.get_request(self.root_uri + chassis) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: chassis_service.append(member[u'@odata.id']) self.chassis_uri_list = chassis_service return {'ret': True} def _find_managers_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Managers' not in data: return {'ret': False, 'msg': "Manager resource not found"} else: manager = data["Managers"]["@odata.id"] response = self.get_request(self.root_uri + manager) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: manager_service = member[u'@odata.id'] self.manager_uri = manager_service return {'ret': True} def get_logs(self): log_svcs_uri_list = [] list_of_logs = [] properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat', 'Message', 'MessageId', 'MessageArgs'] # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data.get('Members', []): response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id']) if response['ret'] is False: return response _data = response['data'] if 'Entries' in _data: log_svcs_uri_list.append(_data['Entries'][u'@odata.id']) # For each entry in LogServices, get log name and all log entries for log_svcs_uri in log_svcs_uri_list: logs = {} list_of_log_entries = [] response = self.get_request(self.root_uri + log_svcs_uri) if response['ret'] is False: return response data = response['data'] logs['Description'] = data.get('Description', 'Collection of log entries') # Get all log entries for each type of log found for logEntry in data.get('Members', []): entry = {} for prop in properties: if prop in logEntry: entry[prop] = logEntry.get(prop) if entry: list_of_log_entries.append(entry) log_name = log_svcs_uri.split('/')[-1] logs[log_name] = list_of_log_entries list_of_logs.append(logs) # list_of_logs[logs{list_of_log_entries[entry{}]}] return {'ret': True, 'entries': list_of_logs} def clear_logs(self): # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data[u'Members']: response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"]) if response['ret'] is False: return response _data = response['data'] # Check to make sure option is available, otherwise error is ugly if "Actions" in _data: if "#LogService.ClearLog" in _data[u"Actions"]: self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {}) if response['ret'] is False: return response return {'ret': True} def aggregate(self, func): ret = True entries = [] for systems_uri in self.systems_uris: inventory = func(systems_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'systems_uri': systems_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_storage_controller_inventory(self, systems_uri): result = {} controller_list = [] controller_results = [] # Get these entries, but does not fail if not found properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers', 'Location', 'Manufacturer', 'Model', 'Name', 'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status'] key = "StorageControllers" # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'Storage' not in data: return {'ret': False, 'msg': "Storage resource not found"} # Get a list of all storage controllers and build respective URIs storage_uri = data['Storage']["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Loop through Members and their StorageControllers # and gather properties from each StorageController if data[u'Members']: for storage_member in data[u'Members']: storage_member_uri = storage_member[u'@odata.id'] response = self.get_request(self.root_uri + storage_member_uri) data = response['data'] if key in data: controller_list = data[key] for controller in controller_list: controller_result = {} for property in properties: if property in controller: controller_result[property] = controller[property] controller_results.append(controller_result) result['entries'] = controller_results return result else: return {'ret': False, 'msg': "Storage resource not found"} def get_multi_storage_controller_inventory(self): return self.aggregate(self.get_storage_controller_inventory) def get_disk_inventory(self, systems_uri): result = {'entries': []} controller_list = [] # Get these entries, but does not fail if not found properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes', 'EncryptionAbility', 'EncryptionStatus', 'FailurePredicted', 'HotspareType', 'Id', 'Identifiers', 'Manufacturer', 'MediaType', 'Model', 'Name', 'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision', 'RotationSpeedRPM', 'SerialNumber', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data[u'Members']: for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] if 'Drives' in data: for device in data[u'Drives']: disk_uri = self.root_uri + device[u'@odata.id'] response = self.get_request(disk_uri) data = response['data'] drive_result = {} for property in properties: if property in data: if data[property] is not None: drive_result[property] = data[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) if 'SimpleStorage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data["SimpleStorage"]["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Name' in data: controller_name = data['Name'] else: sc_id = data.get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] for device in data[u'Devices']: drive_result = {} for property in properties: if property in device: drive_result[property] = device[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) return result def get_multi_disk_inventory(self): return self.aggregate(self.get_disk_inventory) def get_volume_inventory(self, systems_uri): result = {'entries': []} controller_list = [] volume_list = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes', 'Capacity', 'CapacityBytes', 'CapacitySources', 'Encrypted', 'EncryptionTypes', 'Identifiers', 'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities', 'AllocatedPools', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data.get('Members'): for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id volume_results = [] if 'Volumes' in data: # Get a list of all volumes and build respective URIs volumes_uri = data[u'Volumes'][u'@odata.id'] response = self.get_request(self.root_uri + volumes_uri) data = response['data'] if data.get('Members'): for volume in data[u'Members']: volume_list.append(volume[u'@odata.id']) for v in volume_list: uri = self.root_uri + v response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] volume_result = {} for property in properties: if property in data: if data[property] is not None: volume_result[property] = data[property] # Get related Drives Id drive_id_list = [] if 'Links' in data: if 'Drives' in data[u'Links']: for link in data[u'Links'][u'Drives']: drive_id_link = link[u'@odata.id'] drive_id = drive_id_link.split("/")[-1] drive_id_list.append({'Id': drive_id}) volume_result['Linked_drives'] = drive_id_list volume_results.append(volume_result) volumes = {'Controller': controller_name, 'Volumes': volume_results} result["entries"].append(volumes) else: return {'ret': False, 'msg': "Storage resource not found"} return result def get_multi_volume_inventory(self): return self.aggregate(self.get_volume_inventory) def restart_manager_gracefully(self): result = {} key = "Actions" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] action_uri = data[key]["#Manager.Reset"]["target"] payload = {'ResetType': 'GracefulRestart'} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True} def manage_indicator_led(self, command): result = {} key = 'IndicatorLED' payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'} result = {} for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} if command in payloads.keys(): payload = {'IndicatorLED': payloads[command]} response = self.patch_request(self.root_uri + chassis_uri, payload) if response['ret'] is False: return response else: return {'ret': False, 'msg': 'Invalid command'} return result def _map_reset_type(self, reset_type, allowable_values): equiv_types = { 'On': 'ForceOn', 'ForceOn': 'On', 'ForceOff': 'GracefulShutdown', 'GracefulShutdown': 'ForceOff', 'GracefulRestart': 'ForceRestart', 'ForceRestart': 'GracefulRestart' } if reset_type in allowable_values: return reset_type if reset_type not in equiv_types: return reset_type mapped_type = equiv_types[reset_type] if mapped_type in allowable_values: return mapped_type return reset_type def manage_system_power(self, command): key = "Actions" reset_type_values = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] # command should be PowerOn, PowerForceOff, etc. if not command.startswith('Power'): return {'ret': False, 'msg': 'Invalid Command (%s)' % command} reset_type = command[5:] # map Reboot to a ResetType that does a reboot if reset_type == 'Reboot': reset_type = 'GracefulRestart' if reset_type not in reset_type_values: return {'ret': False, 'msg': 'Invalid Command (%s)' % command} # read the system resource and get the current power state response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response data = response['data'] power_state = data.get('PowerState') # if power is already in target state, nothing to do if power_state == "On" and reset_type in ['On', 'ForceOn']: return {'ret': True, 'changed': False} if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']: return {'ret': True, 'changed': False} # get the #ComputerSystem.Reset Action and target URI if key not in data or '#ComputerSystem.Reset' not in data[key]: return {'ret': False, 'msg': 'Action #ComputerSystem.Reset not found'} reset_action = data[key]['#ComputerSystem.Reset'] if 'target' not in reset_action: return {'ret': False, 'msg': 'target URI missing from Action #ComputerSystem.Reset'} action_uri = reset_action['target'] # get AllowableValues from ActionInfo allowable_values = None if '@Redfish.ActionInfo' in reset_action: action_info_uri = reset_action.get('@Redfish.ActionInfo') response = self.get_request(self.root_uri + action_info_uri) if response['ret'] is True: data = response['data'] if 'Parameters' in data: params = data['Parameters'] for param in params: if param.get('Name') == 'ResetType': allowable_values = param.get('AllowableValues') break # fallback to @Redfish.AllowableValues annotation if allowable_values is None: allowable_values = reset_action.get('[email protected]', []) # map ResetType to an allowable value if needed if reset_type not in allowable_values: reset_type = self._map_reset_type(reset_type, allowable_values) # define payload payload = {'ResetType': reset_type} # POST to Action URI response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def _find_account_uri(self, username=None, acct_id=None): if not any((username, acct_id)): return {'ret': False, 'msg': 'Must provide either account_id or account_username'} response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if username: if username == data.get('UserName'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} if acct_id: if acct_id == data.get('Id'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No account with the given account_id or account_username found'} def _find_empty_account_slot(self): response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] if uris: # first slot may be reserved, so move to end of list uris += [uris.pop(0)] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if data.get('UserName') == "" and not data.get('Enabled', True): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No empty account slot found'} def list_users(self): result = {} # listing all users has always been slower than other operations, why? user_list = [] users_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled'] response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for users in data.get('Members', []): user_list.append(users[u'@odata.id']) # user_list[] are URIs # for each user, get details for uri in user_list: user = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: user[property] = data[property] users_results.append(user) result["entries"] = users_results return result def add_user_via_patch(self, user): if user.get('account_id'): # If Id slot specified, use it response = self._find_account_uri(acct_id=user.get('account_id')) else: # Otherwise find first empty slot response = self._find_empty_account_slot() if not response['ret']: return response uri = response['uri'] payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def add_user(self, user): if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_account_uri(username=user.get('account_username')) if response['ret']: # account_username already exists, nothing to do return {'ret': True, 'changed': False} response = self.get_request(self.root_uri + self.accounts_uri) if not response['ret']: return response headers = response['headers'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'POST' not in methods: # if Allow header present and POST not listed, add via PATCH return self.add_user_via_patch(user) payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.post_request(self.root_uri + self.accounts_uri, payload) if not response['ret']: if response.get('status') == 405: # if POST returned a 405, try to add via PATCH return self.add_user_via_patch(user) else: return response return {'ret': True} def enable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('Enabled', True): # account already enabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': True} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user_via_patch(self, user, uri=None, data=None): if not uri: response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data and data.get('UserName') == '' and not data.get('Enabled', False): # account UserName already cleared, nothing to do return {'ret': True, 'changed': False} payload = {'UserName': ''} if 'Enabled' in data: payload['Enabled'] = False response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: if response.get('no_match'): # account does not exist, nothing to do return {'ret': True, 'changed': False} else: # some error encountered return response uri = response['uri'] headers = response['headers'] data = response['data'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'DELETE' not in methods: # if Allow header present and DELETE not listed, del via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) response = self.delete_request(self.root_uri + uri) if not response['ret']: if response.get('status') == 405: # if DELETE returned a 405, try to delete via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) else: return response return {'ret': True} def disable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if not data.get('Enabled'): # account already disabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': False} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_role(self, user): if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('RoleId') == user.get('account_roleid'): # account already has RoleId , nothing to do return {'ret': True, 'changed': False} payload = {'RoleId': user.get('account_roleid')} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_password(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'Password': user['account_password']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_name(self, user): if not user.get('account_updatename'): return {'ret': False, 'msg': 'Must provide account_updatename for UpdateUserName command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'UserName': user['account_updatename']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_accountservice_properties(self, user): if user.get('account_properties') is None: return {'ret': False, 'msg': 'Must provide account_properties for UpdateAccountServiceProperties command'} account_properties = user.get('account_properties') # Find AccountService response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} accountservice_uri = data["AccountService"]["@odata.id"] # Check support or not response = self.get_request(self.root_uri + accountservice_uri) if response['ret'] is False: return response data = response['data'] for property_name in account_properties.keys(): if property_name not in data: return {'ret': False, 'msg': 'property %s not supported' % property_name} # if properties is already matched, nothing to do need_change = False for property_name in account_properties.keys(): if account_properties[property_name] != data[property_name]: need_change = True break if not need_change: return {'ret': True, 'changed': False, 'msg': "AccountService properties already set"} payload = account_properties response = self.patch_request(self.root_uri + accountservice_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified AccountService properties"} def get_sessions(self): result = {} # listing all users has always been slower than other operations, why? session_list = [] sessions_results = [] # Get these entries, but does not fail if not found properties = ['Description', 'Id', 'Name', 'UserName'] response = self.get_request(self.root_uri + self.sessions_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for sessions in data[u'Members']: session_list.append(sessions[u'@odata.id']) # session_list[] are URIs # for each session, get details for uri in session_list: session = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: session[property] = data[property] sessions_results.append(session) result["entries"] = sessions_results return result def get_firmware_update_capabilities(self): result = {} response = self.get_request(self.root_uri + self.update_uri) if response['ret'] is False: return response result['ret'] = True result['entries'] = {} data = response['data'] if "Actions" in data: actions = data['Actions'] if len(actions) > 0: for key in actions.keys(): action = actions.get(key) if 'title' in action: title = action['title'] else: title = key result['entries'][title] = action.get('[email protected]', ["Key [email protected] not found"]) else: return {'ret': "False", 'msg': "Actions list is empty."} else: return {'ret': "False", 'msg': "Key Actions not found."} return result def _software_inventory(self, uri): result = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] result['entries'] = [] for member in data[u'Members']: uri = self.root_uri + member[u'@odata.id'] # Get details for each software or firmware member response = self.get_request(uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] software = {} # Get these standard properties if present for key in ['Name', 'Id', 'Status', 'Version', 'Updateable', 'SoftwareId', 'LowestSupportedVersion', 'Manufacturer', 'ReleaseDate']: if key in data: software[key] = data.get(key) result['entries'].append(software) return result def get_firmware_inventory(self): if self.firmware_uri is None: return {'ret': False, 'msg': 'No FirmwareInventory resource found'} else: return self._software_inventory(self.firmware_uri) def get_software_inventory(self): if self.software_uri is None: return {'ret': False, 'msg': 'No SoftwareInventory resource found'} else: return self._software_inventory(self.software_uri) def get_bios_attributes(self, systems_uri): result = {} bios_attributes = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for attribute in data[u'Attributes'].items(): bios_attributes[attribute[0]] = attribute[1] result["entries"] = bios_attributes return result def get_multi_bios_attributes(self): return self.aggregate(self.get_bios_attributes) def _get_boot_options_dict(self, boot): # Get these entries from BootOption, if present properties = ['DisplayName', 'BootOptionReference'] # Retrieve BootOptions if present if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']: boot_options_uri = boot['BootOptions']["@odata.id"] # Get BootOptions resource response = self.get_request(self.root_uri + boot_options_uri) if response['ret'] is False: return {} data = response['data'] # Retrieve Members array if 'Members' not in data: return {} members = data['Members'] else: members = [] # Build dict of BootOptions keyed by BootOptionReference boot_options_dict = {} for member in members: if '@odata.id' not in member: return {} boot_option_uri = member['@odata.id'] response = self.get_request(self.root_uri + boot_option_uri) if response['ret'] is False: return {} data = response['data'] if 'BootOptionReference' not in data: return {} boot_option_ref = data['BootOptionReference'] # fetch the props to display for this boot device boot_props = {} for prop in properties: if prop in data: boot_props[prop] = data[prop] boot_options_dict[boot_option_ref] = boot_props return boot_options_dict def get_boot_order(self, systems_uri): result = {} # Retrieve System resource response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # Build boot device list boot_device_list = [] for ref in boot_order: boot_device_list.append( boot_options_dict.get(ref, {'BootOptionReference': ref})) result["entries"] = boot_device_list return result def get_multi_boot_order(self): return self.aggregate(self.get_boot_order) def get_boot_override(self, systems_uri): result = {} properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget", "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "[email protected]"] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Boot' not in data: return {'ret': False, 'msg': "Key Boot not found"} boot = data['Boot'] boot_overrides = {} if "BootSourceOverrideEnabled" in boot: if boot["BootSourceOverrideEnabled"] is not False: for property in properties: if property in boot: if boot[property] is not None: boot_overrides[property] = boot[property] else: return {'ret': False, 'msg': "No boot override is enabled."} result['entries'] = boot_overrides return result def get_multi_boot_override(self): return self.aggregate(self.get_boot_override) def set_bios_default_settings(self): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] reset_bios_settings_uri = data["Actions"]["#Bios.ResetBios"]["target"] response = self.post_request(self.root_uri + reset_bios_settings_uri, {}) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Set BIOS to default settings"} def set_one_time_boot_device(self, bootdevice, uefi_target, boot_next): result = {} key = "Boot" if not bootdevice: return {'ret': False, 'msg': "bootdevice option required for SetOneTimeBoot"} # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} boot = data[key] annotation = '[email protected]' if annotation in boot: allowable_values = boot[annotation] if isinstance(allowable_values, list) and bootdevice not in allowable_values: return {'ret': False, 'msg': "Boot device %s not in list of allowable values (%s)" % (bootdevice, allowable_values)} # read existing values enabled = boot.get('BootSourceOverrideEnabled') target = boot.get('BootSourceOverrideTarget') cur_uefi_target = boot.get('UefiTargetBootSourceOverride') cur_boot_next = boot.get('BootNext') if bootdevice == 'UefiTarget': if not uefi_target: return {'ret': False, 'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"} if enabled == 'Once' and target == bootdevice and uefi_target == cur_uefi_target: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'UefiTargetBootSourceOverride': uefi_target } } elif bootdevice == 'UefiBootNext': if not boot_next: return {'ret': False, 'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"} if enabled == 'Once' and target == bootdevice and boot_next == cur_boot_next: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'BootNext': boot_next } } else: if enabled == 'Once' and target == bootdevice: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice } } response = self.patch_request(self.root_uri + self.systems_uris[0], payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def set_bios_attributes(self, attr): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # First, check if BIOS attribute exists if attr['bios_attr_name'] not in data[u'Attributes']: return {'ret': False, 'msg': "BIOS attribute not found"} # Find out if value is already set to what we want. If yes, return if data[u'Attributes'][attr['bios_attr_name']] == attr['bios_attr_value']: return {'ret': True, 'changed': False, 'msg': "BIOS attribute already set"} set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"]["@odata.id"] # Example: bios_attr = {\"name\":\"value\"} bios_attr = "{\"" + attr['bios_attr_name'] + "\":\"" + attr['bios_attr_value'] + "\"}" payload = {"Attributes": json.loads(bios_attr)} response = self.patch_request(self.root_uri + set_bios_attr_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified BIOS attribute"} def set_boot_order(self, boot_list): if not boot_list: return {'ret': False, 'msg': "boot_order list required for SetBootOrder command"} # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # validate boot_list against BootOptionReferences if available if boot_options_dict: boot_option_references = boot_options_dict.keys() for ref in boot_list: if ref not in boot_option_references: return {'ret': False, 'msg': "BootOptionReference %s not found in BootOptions" % ref} # If requested BootOrder is already set, nothing to do if boot_order == boot_list: return {'ret': True, 'changed': False, 'msg': "BootOrder already set to %s" % boot_list} payload = { 'Boot': { 'BootOrder': boot_list } } response = self.patch_request(self.root_uri + systems_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set"} def set_default_boot_order(self): # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # get the #ComputerSystem.SetDefaultBootOrder Action and target URI action = '#ComputerSystem.SetDefaultBootOrder' if 'Actions' not in data or action not in data['Actions']: return {'ret': False, 'msg': 'Action %s not found' % action} if 'target' not in data['Actions'][action]: return {'ret': False, 'msg': 'target URI missing from Action %s' % action} action_uri = data['Actions'][action]['target'] # POST to Action URI payload = {} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set to default"} def get_chassis_inventory(self): result = {} chassis_results = [] # Get these entries, but does not fail if not found properties = ['ChassisType', 'PartNumber', 'AssetTag', 'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] chassis_result = {} for property in properties: if property in data: chassis_result[property] = data[property] chassis_results.append(chassis_result) result["entries"] = chassis_results return result def get_fan_inventory(self): result = {} fan_results = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['FanName', 'Reading', 'ReadingUnits', 'Status'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: # match: found an entry for "Thermal" information = fans thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for device in data[u'Fans']: fan = {} for property in properties: if property in device: fan[property] = device[property] fan_results.append(fan) result["entries"] = fan_results return result def get_chassis_power(self): result = {} key = "Power" # Get these entries, but does not fail if not found properties = ['Name', 'PowerAllocatedWatts', 'PowerAvailableWatts', 'PowerCapacityWatts', 'PowerConsumedWatts', 'PowerMetrics', 'PowerRequestedWatts', 'RelatedItem', 'Status'] chassis_power_results = [] # Go through list for chassis_uri in self.chassis_uri_list: chassis_power_result = {} response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: response = self.get_request(self.root_uri + data[key]['@odata.id']) data = response['data'] if 'PowerControl' in data: if len(data['PowerControl']) > 0: data = data['PowerControl'][0] for property in properties: if property in data: chassis_power_result[property] = data[property] else: return {'ret': False, 'msg': 'Key PowerControl not found.'} chassis_power_results.append(chassis_power_result) else: return {'ret': False, 'msg': 'Key Power not found.'} result['entries'] = chassis_power_results return result def get_chassis_thermals(self): result = {} sensors = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical', 'UpperThresholdFatal', 'UpperThresholdNonCritical', 'LowerThresholdCritical', 'LowerThresholdFatal', 'LowerThresholdNonCritical', 'MaxReadingRangeTemp', 'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem', 'SensorNumber'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if "Temperatures" in data: for sensor in data[u'Temperatures']: sensor_result = {} for property in properties: if property in sensor: if sensor[property] is not None: sensor_result[property] = sensor[property] sensors.append(sensor_result) if sensors is None: return {'ret': False, 'msg': 'Key Temperatures was not found.'} result['entries'] = sensors return result def get_cpu_inventory(self, systems_uri): result = {} cpu_list = [] cpu_results = [] key = "Processors" # Get these entries, but does not fail if not found properties = ['Id', 'Manufacturer', 'Model', 'MaxSpeedMHz', 'TotalCores', 'TotalThreads', 'Status'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} processors_uri = data[key]["@odata.id"] # Get a list of all CPUs and build respective URIs response = self.get_request(self.root_uri + processors_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for cpu in data[u'Members']: cpu_list.append(cpu[u'@odata.id']) for c in cpu_list: cpu = {} uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: cpu[property] = data[property] cpu_results.append(cpu) result["entries"] = cpu_results return result def get_multi_cpu_inventory(self): return self.aggregate(self.get_cpu_inventory) def get_memory_inventory(self, systems_uri): result = {} memory_list = [] memory_results = [] key = "Memory" # Get these entries, but does not fail if not found properties = ['SerialNumber', 'MemoryDeviceType', 'PartNuber', 'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} memory_uri = data[key]["@odata.id"] # Get a list of all DIMMs and build respective URIs response = self.get_request(self.root_uri + memory_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for dimm in data[u'Members']: memory_list.append(dimm[u'@odata.id']) for m in memory_list: dimm = {} uri = self.root_uri + m response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if "Status" in data: if "State" in data["Status"]: if data["Status"]["State"] == "Absent": continue else: continue for property in properties: if property in data: dimm[property] = data[property] memory_results.append(dimm) result["entries"] = memory_results return result def get_multi_memory_inventory(self): return self.aggregate(self.get_memory_inventory) def get_nic_inventory(self, resource_uri): result = {} nic_list = [] nic_results = [] key = "EthernetInterfaces" # Get these entries, but does not fail if not found properties = ['Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses', 'NameServers', 'MACAddress', 'PermanentMACAddress', 'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} ethernetinterfaces_uri = data[key]["@odata.id"] # Get a list of all network controllers and build respective URIs response = self.get_request(self.root_uri + ethernetinterfaces_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for nic in data[u'Members']: nic_list.append(nic[u'@odata.id']) for n in nic_list: nic = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: nic[property] = data[property] nic_results.append(nic) result["entries"] = nic_results return result def get_multi_nic_inventory(self, resource_type): ret = True entries = [] # Given resource_type, use the proper URI if resource_type == 'Systems': resource_uris = self.systems_uris elif resource_type == 'Manager': # put in a list to match what we're doing with systems_uris resource_uris = [self.manager_uri] for resource_uri in resource_uris: inventory = self.get_nic_inventory(resource_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'resource_uri': resource_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_virtualmedia(self, resource_uri): result = {} virtualmedia_list = [] virtualmedia_results = [] key = "VirtualMedia" # Get these entries, but does not fail if not found properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes', 'Image', 'ImageName', 'Name', 'WriteProtected', 'TransferMethod', 'TransferProtocolType'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} virtualmedia_uri = data[key]["@odata.id"] # Get a list of all virtual media and build respective URIs response = self.get_request(self.root_uri + virtualmedia_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for virtualmedia in data[u'Members']: virtualmedia_list.append(virtualmedia[u'@odata.id']) for n in virtualmedia_list: virtualmedia = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: virtualmedia[property] = data[property] virtualmedia_results.append(virtualmedia) result["entries"] = virtualmedia_results return result def get_multi_virtualmedia(self): ret = True entries = [] # Because _find_managers_resource() only find last Manager uri in self.manager_uri, not one list. This should be 1 issue. # I have to put manager_uri into list to reduce future changes when the issue is fixed. resource_uris = [self.manager_uri] for resource_uri in resource_uris: virtualmedia = self.get_virtualmedia(resource_uri) ret = virtualmedia.pop('ret') and ret if 'entries' in virtualmedia: entries.append(({'resource_uri': resource_uri}, virtualmedia['entries'])) return dict(ret=ret, entries=entries) def get_psu_inventory(self): result = {} psu_list = [] psu_results = [] key = "PowerSupplies" # Get these entries, but does not fail if not found properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status'] # Get a list of all Chassis and build URIs, then get all PowerSupplies # from each Power entry in the Chassis chassis_uri_list = self.chassis_uri_list for chassis_uri in chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Power' in data: power_uri = data[u'Power'][u'@odata.id'] else: continue response = self.get_request(self.root_uri + power_uri) data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} psu_list = data[key] for psu in psu_list: psu_not_present = False psu_data = {} for property in properties: if property in psu: if psu[property] is not None: if property == 'Status': if 'State' in psu[property]: if psu[property]['State'] == 'Absent': psu_not_present = True psu_data[property] = psu[property] if psu_not_present: continue psu_results.append(psu_data) result["entries"] = psu_results if not result["entries"]: return {'ret': False, 'msg': "No PowerSupply objects found"} return result def get_multi_psu_inventory(self): return self.aggregate(self.get_psu_inventory) def get_system_inventory(self, systems_uri): result = {} inventory = {} # Get these entries, but does not fail if not found properties = ['Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag', 'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary', 'ProcessorSummary', 'TrustedModules'] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for property in properties: if property in data: inventory[property] = data[property] result["entries"] = inventory return result def get_multi_system_inventory(self): return self.aggregate(self.get_system_inventory) def get_network_protocols(self): result = {} service_result = {} # Find NetworkProtocol response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'NetworkProtocol' not in data: return {'ret': False, 'msg': "NetworkProtocol resource not found"} networkprotocol_uri = data["NetworkProtocol"]["@odata.id"] response = self.get_request(self.root_uri + networkprotocol_uri) if response['ret'] is False: return response data = response['data'] protocol_services = ['SNMP', 'VirtualMedia', 'Telnet', 'SSDP', 'IPMI', 'SSH', 'KVMIP', 'NTP', 'HTTP', 'HTTPS', 'DHCP', 'DHCPv6', 'RDP', 'RFB'] for protocol_service in protocol_services: if protocol_service in data.keys(): service_result[protocol_service] = data[protocol_service] result['ret'] = True result["entries"] = service_result return result def set_network_protocols(self, manager_services): # Check input data validity protocol_services = ['SNMP', 'VirtualMedia', 'Telnet', 'SSDP', 'IPMI', 'SSH', 'KVMIP', 'NTP', 'HTTP', 'HTTPS', 'DHCP', 'DHCPv6', 'RDP', 'RFB'] protocol_state_onlist = ['true', 'True', True, 'on', 1] protocol_state_offlist = ['false', 'False', False, 'off', 0] payload = {} for service_name in manager_services.keys(): if service_name not in protocol_services: return {'ret': False, 'msg': "Service name %s is invalid" % service_name} payload[service_name] = {} for service_property in manager_services[service_name].keys(): value = manager_services[service_name][service_property] if service_property in ['ProtocolEnabled', 'protocolenabled']: if value in protocol_state_onlist: payload[service_name]['ProtocolEnabled'] = True elif value in protocol_state_offlist: payload[service_name]['ProtocolEnabled'] = False else: return {'ret': False, 'msg': "Value of property %s is invalid" % service_property} elif service_property in ['port', 'Port']: if isinstance(value, int): payload[service_name]['Port'] = value elif isinstance(value, str) and value.isdigit(): payload[service_name]['Port'] = int(value) else: return {'ret': False, 'msg': "Value of property %s is invalid" % service_property} else: payload[service_name][service_property] = value # Find NetworkProtocol response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'NetworkProtocol' not in data: return {'ret': False, 'msg': "NetworkProtocol resource not found"} networkprotocol_uri = data["NetworkProtocol"]["@odata.id"] # Check service property support or not response = self.get_request(self.root_uri + networkprotocol_uri) if response['ret'] is False: return response data = response['data'] for service_name in payload.keys(): if service_name not in data: return {'ret': False, 'msg': "%s service not supported" % service_name} for service_property in payload[service_name].keys(): if service_property not in data[service_name]: return {'ret': False, 'msg': "%s property for %s service not supported" % (service_property, service_name)} # if the protocol is already set, nothing to do need_change = False for service_name in payload.keys(): for service_property in payload[service_name].keys(): value = payload[service_name][service_property] if value != data[service_name][service_property]: need_change = True break if not need_change: return {'ret': True, 'changed': False, 'msg': "Manager NetworkProtocol services already set"} response = self.patch_request(self.root_uri + networkprotocol_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified Manager NetworkProtocol services"}
closed
ansible/ansible
https://github.com/ansible/ansible
60,111
redfish_config can't set boot order on Huawei server (multiple attributes required)
##### SUMMARY Trying to set the boot order on a Huawei 2288H V5 via iBMC/redfish, redfish_config module fails because it needs to set the 4 `BootTypeOrderX` at the same time, and we currently only have the option to set 1 at a time This report is in between `Bug Report` and `Feature Idea` ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME redfish_config ##### ANSIBLE VERSION ``` ansible 2.9.0.dev0 config file = /home/echampetier/git/ops/provisioning/ansible.cfg configured module search path = [u'/home/echampetier/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /usr/bin/ansible python version = 2.7.16 (default, Apr 30 2019, 15:54:43) [GCC 9.0.1 20190312 (Red Hat 9.0.1-0.10)] ``` ##### CONFIGURATION ``` ANSIBLE_PIPELINING(/home/echampetier/git/ops/provisioning/ansible.cfg) = True DEFAULT_CALLBACK_WHITELIST(/home/echampetier/git/ops/provisioning/ansible.cfg) = [u'profile_tasks'] DEFAULT_REMOTE_USER(/home/echampetier/git/ops/provisioning/ansible.cfg) = root ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> Fedora 30 Huawei 2288H V5 with iBMC 3.55 (U4282) ##### STEPS TO REPRODUCE ```yaml - name: Set Bios config redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: "BootTypeOrder0" bios_attribute_value: "Others" baseuri: "{{ ibmc_ip }}" username: "{{ ibmc_user }}" password: "{{ ibmc_pass }}" delegate_to: localhost ``` ##### EXPECTED RESULTS It works ! ##### ACTUAL RESULTS ``` Using module file /usr/lib/python2.7/site-packages/ansible/modules/remote_management/redfish/redfish_config.py Pipelining is enabled. <localhost> ESTABLISH LOCAL CONNECTION FOR USER: echampetier <localhost> EXEC /bin/sh -c '/usr/bin/python2 && sleep 0' fatal: [192.168.1.3 -> localhost]: FAILED! => { "changed": false, "invocation": { "module_args": { "baseuri": "192.168.1.2", "bios_attribute_name": "BootTypeOrder0", "bios_attribute_value": "Others", "category": "Systems", "command": [ "SetBiosAttributes" ], "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "timeout": 10, "username": "Administrator" } }, "msg": "HTTP Error 400 on PATCH request to 'https://192.168.1.2/redfish/v1/Systems/1/Bios/Settings', extended message: 'Failed to set the BIOS boot order.'" } ``` When using curl: ``` $ curl -u 'Administrator:<redacted>' -XPATCH https://192.168.1.2/redfish/v1/Systems/1/Bios/Settings -d '{"Attributes": {"BootTypeOrder0": "Others"}}' -k -vvv -H 'Content-Type: application/json' -H 'If-Match: W/"6168147f"' -s | jq . ... < HTTP/1.1 400 Bad Request < Date: Mon, 05 Aug 2019 21:31:18 GMT < X-Frame-Options: SAMEORIGIN < X-Download-Options: noopen < Content-Security-Policy: default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self' wss://*:*; img-src 'self' data:; frame-src 'self'; font-src 'self'; object-src 'self'; style-src 'self' 'unsafe-inline' < OData-Version: 4.0 < Cache-Control: max-age=0, no-cache, no-store, must-revalidate < Content-Length: 535 < X-XSS-Protection: 1; mode=block < Strict-Transport-Security: max-age=31536000; includeSubDomains < X-Content-Type-Options: nosniff < Expires: 0 < Connection: close < Content-Type: application/json;charset=utf-8 { "error": { "code": "Base.1.0.GeneralError", "message": "A general error has occurred. See ExtendedInfo for more information.", "@Message.ExtendedInfo": [ { "@odata.type": "/redfish/v1/$metadata#MessageRegistry.1.0.0.MessageRegistry", "MessageId": "iBMC.1.0.SettingBootOrderFailed", "RelatedProperties": [], "Message": "Failed to set the BIOS boot order.", "MessageArgs": [], "Severity": "Warning", "Resolution": "Check that the four property names are correct, all the four properties are set, and the property values are different from each other." } ] } } ``` And when sending the 4 at the same time it works ``` $ curl -u 'Administrator:<redacted>' -XPATCH https://192.168.1.2/redfish/v1/Systems/1/Bios/Settings -d '{"Attributes": {"BootTypeOrder0":"Others", "BootTypeOrder1":"HardDiskDrive", "BootTypeOrder2":"DVDROMDrive", "BootTypeOrder3":"PXE"}}' -k -vvv -H 'Content-Type: application/json' -H 'If-Match: W/"6168147f"' -s | jq . ... < HTTP/1.1 200 OK < Date: Mon, 05 Aug 2019 21:34:08 GMT < X-Frame-Options: SAMEORIGIN < X-Download-Options: noopen < Content-Security-Policy: default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self' wss://*:*; img-src 'self' data:; frame-src 'self'; font-src 'self'; object-src 'self'; style-src 'self' 'unsafe-inline' < OData-Version: 4.0 < Cache-Control: max-age=0, no-cache, no-store, must-revalidate < ETag: W/"7d41337e" < Content-Length: 705 < X-XSS-Protection: 1; mode=block < Strict-Transport-Security: max-age=31536000; includeSubDomains < X-Content-Type-Options: nosniff < Expires: 0 < Content-Type: application/json;charset=utf-8 < { "@odata.context": "/redfish/v1/$metadata#Systems/Members/1/Bios/Settings/$entity", "@odata.id": "/redfish/v1/Systems/1/Bios/Settings", "@odata.type": "#Bios.v1_0_0.Bios", "Id": "Settings", "Name": "BIOS Configuration Pending Settings", "AttributeRegistry": "BiosAttributeRegistry.1.9.9", "Attributes": { "BootTypeOrder0": "Others", "BootTypeOrder1": "HardDiskDrive", "BootTypeOrder2": "DVDROMDrive", "BootTypeOrder3": "PXE" }, "Actions": { "Oem": { "Huawei": { "#Settings.Revoke": { "target": "/redfish/v1/Systems/1/Bios/Settings/Actions/Oem/Huawei/Settings.Revoke", "@Redfish.ActionInfo": "/redfish/v1/Systems/1/Bios/Settings/SettingsRevokeActionInfo" } } } } } ```
https://github.com/ansible/ansible/issues/60111
https://github.com/ansible/ansible/pull/62764
ec1c5585af424f4c43fa7a16cbf82c2571045415
b4cd9086dca54ae2865d6c54917924959ecf9eb8
2019-08-05T21:43:24Z
python
2019-10-31T14:47:05Z
lib/ansible/modules/remote_management/redfish/redfish_config.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_config version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to set or update a configuration attribute. - Manages BIOS configuration settings. - Manages OOB controller configuration settings. options: category: required: true description: - Category to execute on OOB controller type: str command: required: true description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - User for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str bios_attribute_name: required: false description: - name of BIOS attribute to update default: 'null' type: str version_added: "2.8" bios_attribute_value: required: false description: - value of BIOS attribute to update default: 'null' type: str version_added: "2.8" timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: "2.8" boot_order: required: false description: - list of BootOptionReference strings specifying the BootOrder default: [] type: list version_added: "2.10" network_protocols: required: false description: - setting dict of manager services to update type: dict version_added: "2.10" author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Set BootMode to UEFI redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: BootMode bios_attribute_value: Uefi baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set BootMode to Legacy BIOS redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: BootMode bios_attribute_value: Bios baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Enable PXE Boot for NIC1 redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: PxeDev1EnDis bios_attribute_value: Enabled baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set BIOS default settings with a timeout of 20 seconds redfish_config: category: Systems command: SetBiosDefaultSettings baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 - name: Set boot order redfish_config: category: Systems command: SetBootOrder boot_order: - Boot0002 - Boot0001 - Boot0000 - Boot0003 - Boot0004 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set boot order to the default redfish_config: category: Systems command: SetDefaultBootOrder baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set Manager Network Protocols redfish_config: category: Manager command: SetNetworkProtocols network_protocols: SNMP: ProtocolEnabled: True Port: 161 HTTP: ProtocolEnabled: False Port: 8080 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native # More will be added as module features are expanded CATEGORY_COMMANDS_ALL = { "Systems": ["SetBiosDefaultSettings", "SetBiosAttributes", "SetBootOrder", "SetDefaultBootOrder"], "Manager": ["SetNetworkProtocols"] } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), bios_attribute_name=dict(default='null'), bios_attribute_value=dict(default='null'), timeout=dict(type='int', default=10), boot_order=dict(type='list', elements='str', default=[]), network_protocols=dict( type='dict', default={} ) ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # BIOS attributes to update bios_attributes = {'bios_attr_name': module.params['bios_attribute_name'], 'bios_attr_value': module.params['bios_attribute_value']} # boot order boot_order = module.params['boot_order'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetBiosDefaultSettings": result = rf_utils.set_bios_default_settings() elif command == "SetBiosAttributes": result = rf_utils.set_bios_attributes(bios_attributes) elif command == "SetBootOrder": result = rf_utils.set_boot_order(boot_order) elif command == "SetDefaultBootOrder": result = rf_utils.set_default_boot_order() elif category == "Manager": # execute only if we find a Manager service resource result = rf_utils._find_managers_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetNetworkProtocols": result = rf_utils.set_network_protocols(module.params['network_protocols']) # Return data back or fail with proper message if result['ret'] is True: module.exit_json(changed=result['changed'], msg=to_native(result['msg'])) else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
58,467
Redfish commands need way to specify single system, manager or chassis
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> A number of the existing Redfish commands act on a single system, manager or chassis. But there is no option to specify which one to act on if there are multiple systems, managers or chassis in the service. Currently, in this case, the module will act on the first one in the collection. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_utils.py redfish_config.py redfish_command.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Given the issue summarized above, it is impossible to issue certain commands to systems, managers and chassis beyond the first one that appears in the collection. To solve this, the behavior will be updated as follows: - New options to specify a particular system, manager or chassis will be added. - For the impacted commands (see below), if there is exactly one system/manager/chassis resource in the service, act on that resource. Specifying the system/manager/chassis using the new options will not be required. - In the case where there are multiple system/manager/chassis resources, the one to act on ~~must~~ should be specified using the new options. If one is not specified, ~~an error~~ a deprecation warning will be reported and ~~no action taken~~ the existing behavior of using the first resource in the collection will be used. Here are the impacted commands. Commands that act on a single **system**: - Power* (PowerOn, PowerReboot, etc.) - SetOneTimeBoot - SetBiosDefaultSettings - SetBiosAttributes Commands that act on a single **manager**: - GracefulRestart - ClearLogs Commands that act on a single **chassis**: - IndicatorLedOn, IndicatorLedOff, IndicatorLedBlink <!--- Paste example playbooks or commands between quotes below --> An example of an existing playbook to reboot a system: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` An example of the playbook after adding a new option to specify the system to reboot: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot system_id: 437XR1138R2 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` **Note:** When implementing this feature, but sure to fix any places that may result in errors like: `The value Lit for the property IndicatorLED is not in the list of acceptable values` `Key IndicatorLED not found` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/58467
https://github.com/ansible/ansible/pull/62921
c3838b5d7340e0b6e2abae3fc17a38092fddff71
4349ab57779679d273a61cff88347a5416fac05e
2019-06-27T16:05:09Z
python
2019-10-31T22:09:48Z
lib/ansible/module_utils/redfish_utils.py
# Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import json from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import http_client from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError GET_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} POST_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} PATCH_HEADERS = {'content-type': 'application/json', 'accept': 'application/json', 'OData-Version': '4.0'} DELETE_HEADERS = {'accept': 'application/json', 'OData-Version': '4.0'} class RedfishUtils(object): def __init__(self, creds, root_uri, timeout, module): self.root_uri = root_uri self.creds = creds self.timeout = timeout self.module = module self.service_root = '/redfish/v1/' self._init_session() # The following functions are to send GET/POST/PATCH/DELETE requests def get_request(self, uri): try: resp = open_url(uri, method="GET", headers=GET_HEADERS, url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) data = json.loads(resp.read()) headers = dict((k.lower(), v) for (k, v) in resp.info().items()) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on GET request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on GET request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed GET request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'data': data, 'headers': headers} def post_request(self, uri, pyld): try: resp = open_url(uri, data=json.dumps(pyld), headers=POST_HEADERS, method="POST", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on POST request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on POST request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed POST request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def patch_request(self, uri, pyld): headers = PATCH_HEADERS r = self.get_request(uri) if r['ret']: # Get etag from etag header or @odata.etag property etag = r['headers'].get('etag') if not etag: etag = r['data'].get('@odata.etag') if etag: # Make copy of headers and add If-Match header headers = dict(headers) headers['If-Match'] = etag try: resp = open_url(uri, data=json.dumps(pyld), headers=headers, method="PATCH", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on PATCH request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on PATCH request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed PATCH request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} def delete_request(self, uri, pyld=None): try: data = json.dumps(pyld) if pyld else None resp = open_url(uri, data=data, headers=DELETE_HEADERS, method="DELETE", url_username=self.creds['user'], url_password=self.creds['pswd'], force_basic_auth=True, validate_certs=False, follow_redirects='all', use_proxy=False, timeout=self.timeout) except HTTPError as e: msg = self._get_extended_message(e) return {'ret': False, 'msg': "HTTP Error %s on DELETE request to '%s', extended message: '%s'" % (e.code, uri, msg), 'status': e.code} except URLError as e: return {'ret': False, 'msg': "URL Error on DELETE request to '%s': '%s'" % (uri, e.reason)} # Almost all errors should be caught above, but just in case except Exception as e: return {'ret': False, 'msg': "Failed DELETE request to '%s': '%s'" % (uri, to_text(e))} return {'ret': True, 'resp': resp} @staticmethod def _get_extended_message(error): """ Get Redfish ExtendedInfo message from response payload if present :param error: an HTTPError exception :type error: HTTPError :return: the ExtendedInfo message if present, else standard HTTP error """ msg = http_client.responses.get(error.code, '') if error.code >= 400: try: body = error.read().decode('utf-8') data = json.loads(body) ext_info = data['error']['@Message.ExtendedInfo'] msg = ext_info[0]['Message'] except Exception: pass return msg def _init_session(self): pass def _find_accountservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} else: account_service = data["AccountService"]["@odata.id"] response = self.get_request(self.root_uri + account_service) if response['ret'] is False: return response data = response['data'] accounts = data['Accounts']['@odata.id'] if accounts[-1:] == '/': accounts = accounts[:-1] self.accounts_uri = accounts return {'ret': True} def _find_sessionservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'SessionService' not in data: return {'ret': False, 'msg': "SessionService resource not found"} else: session_service = data["SessionService"]["@odata.id"] response = self.get_request(self.root_uri + session_service) if response['ret'] is False: return response data = response['data'] sessions = data['Sessions']['@odata.id'] if sessions[-1:] == '/': sessions = sessions[:-1] self.sessions_uri = sessions return {'ret': True} def _find_systems_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Systems' not in data: return {'ret': False, 'msg': "Systems resource not found"} response = self.get_request(self.root_uri + data['Systems']['@odata.id']) if response['ret'] is False: return response self.systems_uris = [ i['@odata.id'] for i in response['data'].get('Members', [])] if not self.systems_uris: return { 'ret': False, 'msg': "ComputerSystem's Members array is either empty or missing"} return {'ret': True} def _find_updateservice_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'UpdateService' not in data: return {'ret': False, 'msg': "UpdateService resource not found"} else: update = data["UpdateService"]["@odata.id"] self.update_uri = update response = self.get_request(self.root_uri + update) if response['ret'] is False: return response data = response['data'] self.firmware_uri = self.software_uri = None if 'FirmwareInventory' in data: self.firmware_uri = data['FirmwareInventory'][u'@odata.id'] if 'SoftwareInventory' in data: self.software_uri = data['SoftwareInventory'][u'@odata.id'] return {'ret': True} def _find_chassis_resource(self): chassis_service = [] response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Chassis' not in data: return {'ret': False, 'msg': "Chassis resource not found"} else: chassis = data["Chassis"]["@odata.id"] response = self.get_request(self.root_uri + chassis) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: chassis_service.append(member[u'@odata.id']) self.chassis_uri_list = chassis_service return {'ret': True} def _find_managers_resource(self): response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'Managers' not in data: return {'ret': False, 'msg': "Manager resource not found"} else: manager = data["Managers"]["@odata.id"] response = self.get_request(self.root_uri + manager) if response['ret'] is False: return response data = response['data'] for member in data[u'Members']: manager_service = member[u'@odata.id'] self.manager_uri = manager_service return {'ret': True} def get_logs(self): log_svcs_uri_list = [] list_of_logs = [] properties = ['Severity', 'Created', 'EntryType', 'OemRecordFormat', 'Message', 'MessageId', 'MessageArgs'] # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data.get('Members', []): response = self.get_request(self.root_uri + log_svcs_entry[u'@odata.id']) if response['ret'] is False: return response _data = response['data'] if 'Entries' in _data: log_svcs_uri_list.append(_data['Entries'][u'@odata.id']) # For each entry in LogServices, get log name and all log entries for log_svcs_uri in log_svcs_uri_list: logs = {} list_of_log_entries = [] response = self.get_request(self.root_uri + log_svcs_uri) if response['ret'] is False: return response data = response['data'] logs['Description'] = data.get('Description', 'Collection of log entries') # Get all log entries for each type of log found for logEntry in data.get('Members', []): entry = {} for prop in properties: if prop in logEntry: entry[prop] = logEntry.get(prop) if entry: list_of_log_entries.append(entry) log_name = log_svcs_uri.split('/')[-1] logs[log_name] = list_of_log_entries list_of_logs.append(logs) # list_of_logs[logs{list_of_log_entries[entry{}]}] return {'ret': True, 'entries': list_of_logs} def clear_logs(self): # Find LogService response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'LogServices' not in data: return {'ret': False, 'msg': "LogServices resource not found"} # Find all entries in LogServices logs_uri = data["LogServices"]["@odata.id"] response = self.get_request(self.root_uri + logs_uri) if response['ret'] is False: return response data = response['data'] for log_svcs_entry in data[u'Members']: response = self.get_request(self.root_uri + log_svcs_entry["@odata.id"]) if response['ret'] is False: return response _data = response['data'] # Check to make sure option is available, otherwise error is ugly if "Actions" in _data: if "#LogService.ClearLog" in _data[u"Actions"]: self.post_request(self.root_uri + _data[u"Actions"]["#LogService.ClearLog"]["target"], {}) if response['ret'] is False: return response return {'ret': True} def aggregate(self, func): ret = True entries = [] for systems_uri in self.systems_uris: inventory = func(systems_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'systems_uri': systems_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_storage_controller_inventory(self, systems_uri): result = {} controller_list = [] controller_results = [] # Get these entries, but does not fail if not found properties = ['CacheSummary', 'FirmwareVersion', 'Identifiers', 'Location', 'Manufacturer', 'Model', 'Name', 'PartNumber', 'SerialNumber', 'SpeedGbps', 'Status'] key = "StorageControllers" # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'Storage' not in data: return {'ret': False, 'msg': "Storage resource not found"} # Get a list of all storage controllers and build respective URIs storage_uri = data['Storage']["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Loop through Members and their StorageControllers # and gather properties from each StorageController if data[u'Members']: for storage_member in data[u'Members']: storage_member_uri = storage_member[u'@odata.id'] response = self.get_request(self.root_uri + storage_member_uri) data = response['data'] if key in data: controller_list = data[key] for controller in controller_list: controller_result = {} for property in properties: if property in controller: controller_result[property] = controller[property] controller_results.append(controller_result) result['entries'] = controller_results return result else: return {'ret': False, 'msg': "Storage resource not found"} def get_multi_storage_controller_inventory(self): return self.aggregate(self.get_storage_controller_inventory) def get_disk_inventory(self, systems_uri): result = {'entries': []} controller_list = [] # Get these entries, but does not fail if not found properties = ['BlockSizeBytes', 'CapableSpeedGbs', 'CapacityBytes', 'EncryptionAbility', 'EncryptionStatus', 'FailurePredicted', 'HotspareType', 'Id', 'Identifiers', 'Manufacturer', 'MediaType', 'Model', 'Name', 'PartNumber', 'PhysicalLocation', 'Protocol', 'Revision', 'RotationSpeedRPM', 'SerialNumber', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data[u'Members']: for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] if 'Drives' in data: for device in data[u'Drives']: disk_uri = self.root_uri + device[u'@odata.id'] response = self.get_request(disk_uri) data = response['data'] drive_result = {} for property in properties: if property in data: if data[property] is not None: drive_result[property] = data[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) if 'SimpleStorage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data["SimpleStorage"]["@odata.id"] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if 'Name' in data: controller_name = data['Name'] else: sc_id = data.get('Id', '1') controller_name = 'Controller %s' % sc_id drive_results = [] for device in data[u'Devices']: drive_result = {} for property in properties: if property in device: drive_result[property] = device[property] drive_results.append(drive_result) drives = {'Controller': controller_name, 'Drives': drive_results} result["entries"].append(drives) return result def get_multi_disk_inventory(self): return self.aggregate(self.get_disk_inventory) def get_volume_inventory(self, systems_uri): result = {'entries': []} controller_list = [] volume_list = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'RAIDType', 'VolumeType', 'BlockSizeBytes', 'Capacity', 'CapacityBytes', 'CapacitySources', 'Encrypted', 'EncryptionTypes', 'Identifiers', 'Operations', 'OptimumIOSizeBytes', 'AccessCapabilities', 'AllocatedPools', 'Status'] # Find Storage service response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] if 'SimpleStorage' not in data and 'Storage' not in data: return {'ret': False, 'msg': "SimpleStorage and Storage resource \ not found"} if 'Storage' in data: # Get a list of all storage controllers and build respective URIs storage_uri = data[u'Storage'][u'@odata.id'] response = self.get_request(self.root_uri + storage_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if data.get('Members'): for controller in data[u'Members']: controller_list.append(controller[u'@odata.id']) for c in controller_list: uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] controller_name = 'Controller 1' if 'StorageControllers' in data: sc = data['StorageControllers'] if sc: if 'Name' in sc[0]: controller_name = sc[0]['Name'] else: sc_id = sc[0].get('Id', '1') controller_name = 'Controller %s' % sc_id volume_results = [] if 'Volumes' in data: # Get a list of all volumes and build respective URIs volumes_uri = data[u'Volumes'][u'@odata.id'] response = self.get_request(self.root_uri + volumes_uri) data = response['data'] if data.get('Members'): for volume in data[u'Members']: volume_list.append(volume[u'@odata.id']) for v in volume_list: uri = self.root_uri + v response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] volume_result = {} for property in properties: if property in data: if data[property] is not None: volume_result[property] = data[property] # Get related Drives Id drive_id_list = [] if 'Links' in data: if 'Drives' in data[u'Links']: for link in data[u'Links'][u'Drives']: drive_id_link = link[u'@odata.id'] drive_id = drive_id_link.split("/")[-1] drive_id_list.append({'Id': drive_id}) volume_result['Linked_drives'] = drive_id_list volume_results.append(volume_result) volumes = {'Controller': controller_name, 'Volumes': volume_results} result["entries"].append(volumes) else: return {'ret': False, 'msg': "Storage resource not found"} return result def get_multi_volume_inventory(self): return self.aggregate(self.get_volume_inventory) def restart_manager_gracefully(self): result = {} key = "Actions" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] action_uri = data[key]["#Manager.Reset"]["target"] payload = {'ResetType': 'GracefulRestart'} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True} def manage_indicator_led(self, command): result = {} key = 'IndicatorLED' payloads = {'IndicatorLedOn': 'Lit', 'IndicatorLedOff': 'Off', "IndicatorLedBlink": 'Blinking'} result = {} for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} if command in payloads.keys(): payload = {'IndicatorLED': payloads[command]} response = self.patch_request(self.root_uri + chassis_uri, payload) if response['ret'] is False: return response else: return {'ret': False, 'msg': 'Invalid command'} return result def _map_reset_type(self, reset_type, allowable_values): equiv_types = { 'On': 'ForceOn', 'ForceOn': 'On', 'ForceOff': 'GracefulShutdown', 'GracefulShutdown': 'ForceOff', 'GracefulRestart': 'ForceRestart', 'ForceRestart': 'GracefulRestart' } if reset_type in allowable_values: return reset_type if reset_type not in equiv_types: return reset_type mapped_type = equiv_types[reset_type] if mapped_type in allowable_values: return mapped_type return reset_type def manage_system_power(self, command): key = "Actions" reset_type_values = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] # command should be PowerOn, PowerForceOff, etc. if not command.startswith('Power'): return {'ret': False, 'msg': 'Invalid Command (%s)' % command} reset_type = command[5:] # map Reboot to a ResetType that does a reboot if reset_type == 'Reboot': reset_type = 'GracefulRestart' if reset_type not in reset_type_values: return {'ret': False, 'msg': 'Invalid Command (%s)' % command} # read the system resource and get the current power state response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response data = response['data'] power_state = data.get('PowerState') # if power is already in target state, nothing to do if power_state == "On" and reset_type in ['On', 'ForceOn']: return {'ret': True, 'changed': False} if power_state == "Off" and reset_type in ['GracefulShutdown', 'ForceOff']: return {'ret': True, 'changed': False} # get the #ComputerSystem.Reset Action and target URI if key not in data or '#ComputerSystem.Reset' not in data[key]: return {'ret': False, 'msg': 'Action #ComputerSystem.Reset not found'} reset_action = data[key]['#ComputerSystem.Reset'] if 'target' not in reset_action: return {'ret': False, 'msg': 'target URI missing from Action #ComputerSystem.Reset'} action_uri = reset_action['target'] # get AllowableValues from ActionInfo allowable_values = None if '@Redfish.ActionInfo' in reset_action: action_info_uri = reset_action.get('@Redfish.ActionInfo') response = self.get_request(self.root_uri + action_info_uri) if response['ret'] is True: data = response['data'] if 'Parameters' in data: params = data['Parameters'] for param in params: if param.get('Name') == 'ResetType': allowable_values = param.get('AllowableValues') break # fallback to @Redfish.AllowableValues annotation if allowable_values is None: allowable_values = reset_action.get('[email protected]', []) # map ResetType to an allowable value if needed if reset_type not in allowable_values: reset_type = self._map_reset_type(reset_type, allowable_values) # define payload payload = {'ResetType': reset_type} # POST to Action URI response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def _find_account_uri(self, username=None, acct_id=None): if not any((username, acct_id)): return {'ret': False, 'msg': 'Must provide either account_id or account_username'} response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if username: if username == data.get('UserName'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} if acct_id: if acct_id == data.get('Id'): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No account with the given account_id or account_username found'} def _find_empty_account_slot(self): response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response data = response['data'] uris = [a.get('@odata.id') for a in data.get('Members', []) if a.get('@odata.id')] if uris: # first slot may be reserved, so move to end of list uris += [uris.pop(0)] for uri in uris: response = self.get_request(self.root_uri + uri) if response['ret'] is False: continue data = response['data'] headers = response['headers'] if data.get('UserName') == "" and not data.get('Enabled', True): return {'ret': True, 'data': data, 'headers': headers, 'uri': uri} return {'ret': False, 'no_match': True, 'msg': 'No empty account slot found'} def list_users(self): result = {} # listing all users has always been slower than other operations, why? user_list = [] users_results = [] # Get these entries, but does not fail if not found properties = ['Id', 'Name', 'UserName', 'RoleId', 'Locked', 'Enabled'] response = self.get_request(self.root_uri + self.accounts_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for users in data.get('Members', []): user_list.append(users[u'@odata.id']) # user_list[] are URIs # for each user, get details for uri in user_list: user = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: user[property] = data[property] users_results.append(user) result["entries"] = users_results return result def add_user_via_patch(self, user): if user.get('account_id'): # If Id slot specified, use it response = self._find_account_uri(acct_id=user.get('account_id')) else: # Otherwise find first empty slot response = self._find_empty_account_slot() if not response['ret']: return response uri = response['uri'] payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def add_user(self, user): if not user.get('account_username'): return {'ret': False, 'msg': 'Must provide account_username for AddUser command'} response = self._find_account_uri(username=user.get('account_username')) if response['ret']: # account_username already exists, nothing to do return {'ret': True, 'changed': False} response = self.get_request(self.root_uri + self.accounts_uri) if not response['ret']: return response headers = response['headers'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'POST' not in methods: # if Allow header present and POST not listed, add via PATCH return self.add_user_via_patch(user) payload = {} if user.get('account_username'): payload['UserName'] = user.get('account_username') if user.get('account_password'): payload['Password'] = user.get('account_password') if user.get('account_roleid'): payload['RoleId'] = user.get('account_roleid') response = self.post_request(self.root_uri + self.accounts_uri, payload) if not response['ret']: if response.get('status') == 405: # if POST returned a 405, try to add via PATCH return self.add_user_via_patch(user) else: return response return {'ret': True} def enable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('Enabled', True): # account already enabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': True} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user_via_patch(self, user, uri=None, data=None): if not uri: response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data and data.get('UserName') == '' and not data.get('Enabled', False): # account UserName already cleared, nothing to do return {'ret': True, 'changed': False} payload = {'UserName': ''} if 'Enabled' in data: payload['Enabled'] = False response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def delete_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: if response.get('no_match'): # account does not exist, nothing to do return {'ret': True, 'changed': False} else: # some error encountered return response uri = response['uri'] headers = response['headers'] data = response['data'] if 'allow' in headers: methods = [m.strip() for m in headers.get('allow').split(',')] if 'DELETE' not in methods: # if Allow header present and DELETE not listed, del via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) response = self.delete_request(self.root_uri + uri) if not response['ret']: if response.get('status') == 405: # if DELETE returned a 405, try to delete via PATCH return self.delete_user_via_patch(user, uri=uri, data=data) else: return response return {'ret': True} def disable_user(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if not data.get('Enabled'): # account already disabled, nothing to do return {'ret': True, 'changed': False} payload = {'Enabled': False} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_role(self, user): if not user.get('account_roleid'): return {'ret': False, 'msg': 'Must provide account_roleid for UpdateUserRole command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] data = response['data'] if data.get('RoleId') == user.get('account_roleid'): # account already has RoleId , nothing to do return {'ret': True, 'changed': False} payload = {'RoleId': user.get('account_roleid')} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_password(self, user): response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'Password': user['account_password']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_user_name(self, user): if not user.get('account_updatename'): return {'ret': False, 'msg': 'Must provide account_updatename for UpdateUserName command'} response = self._find_account_uri(username=user.get('account_username'), acct_id=user.get('account_id')) if not response['ret']: return response uri = response['uri'] payload = {'UserName': user['account_updatename']} response = self.patch_request(self.root_uri + uri, payload) if response['ret'] is False: return response return {'ret': True} def update_accountservice_properties(self, user): if user.get('account_properties') is None: return {'ret': False, 'msg': 'Must provide account_properties for UpdateAccountServiceProperties command'} account_properties = user.get('account_properties') # Find AccountService response = self.get_request(self.root_uri + self.service_root) if response['ret'] is False: return response data = response['data'] if 'AccountService' not in data: return {'ret': False, 'msg': "AccountService resource not found"} accountservice_uri = data["AccountService"]["@odata.id"] # Check support or not response = self.get_request(self.root_uri + accountservice_uri) if response['ret'] is False: return response data = response['data'] for property_name in account_properties.keys(): if property_name not in data: return {'ret': False, 'msg': 'property %s not supported' % property_name} # if properties is already matched, nothing to do need_change = False for property_name in account_properties.keys(): if account_properties[property_name] != data[property_name]: need_change = True break if not need_change: return {'ret': True, 'changed': False, 'msg': "AccountService properties already set"} payload = account_properties response = self.patch_request(self.root_uri + accountservice_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified AccountService properties"} def get_sessions(self): result = {} # listing all users has always been slower than other operations, why? session_list = [] sessions_results = [] # Get these entries, but does not fail if not found properties = ['Description', 'Id', 'Name', 'UserName'] response = self.get_request(self.root_uri + self.sessions_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for sessions in data[u'Members']: session_list.append(sessions[u'@odata.id']) # session_list[] are URIs # for each session, get details for uri in session_list: session = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: session[property] = data[property] sessions_results.append(session) result["entries"] = sessions_results return result def get_firmware_update_capabilities(self): result = {} response = self.get_request(self.root_uri + self.update_uri) if response['ret'] is False: return response result['ret'] = True result['entries'] = {} data = response['data'] if "Actions" in data: actions = data['Actions'] if len(actions) > 0: for key in actions.keys(): action = actions.get(key) if 'title' in action: title = action['title'] else: title = key result['entries'][title] = action.get('[email protected]', ["Key [email protected] not found"]) else: return {'ret': "False", 'msg': "Actions list is empty."} else: return {'ret': "False", 'msg': "Key Actions not found."} return result def _software_inventory(self, uri): result = {} response = self.get_request(self.root_uri + uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] result['entries'] = [] for member in data[u'Members']: uri = self.root_uri + member[u'@odata.id'] # Get details for each software or firmware member response = self.get_request(uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] software = {} # Get these standard properties if present for key in ['Name', 'Id', 'Status', 'Version', 'Updateable', 'SoftwareId', 'LowestSupportedVersion', 'Manufacturer', 'ReleaseDate']: if key in data: software[key] = data.get(key) result['entries'].append(software) return result def get_firmware_inventory(self): if self.firmware_uri is None: return {'ret': False, 'msg': 'No FirmwareInventory resource found'} else: return self._software_inventory(self.firmware_uri) def get_software_inventory(self): if self.software_uri is None: return {'ret': False, 'msg': 'No SoftwareInventory resource found'} else: return self._software_inventory(self.software_uri) def get_bios_attributes(self, systems_uri): result = {} bios_attributes = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for attribute in data[u'Attributes'].items(): bios_attributes[attribute[0]] = attribute[1] result["entries"] = bios_attributes return result def get_multi_bios_attributes(self): return self.aggregate(self.get_bios_attributes) def _get_boot_options_dict(self, boot): # Get these entries from BootOption, if present properties = ['DisplayName', 'BootOptionReference'] # Retrieve BootOptions if present if 'BootOptions' in boot and '@odata.id' in boot['BootOptions']: boot_options_uri = boot['BootOptions']["@odata.id"] # Get BootOptions resource response = self.get_request(self.root_uri + boot_options_uri) if response['ret'] is False: return {} data = response['data'] # Retrieve Members array if 'Members' not in data: return {} members = data['Members'] else: members = [] # Build dict of BootOptions keyed by BootOptionReference boot_options_dict = {} for member in members: if '@odata.id' not in member: return {} boot_option_uri = member['@odata.id'] response = self.get_request(self.root_uri + boot_option_uri) if response['ret'] is False: return {} data = response['data'] if 'BootOptionReference' not in data: return {} boot_option_ref = data['BootOptionReference'] # fetch the props to display for this boot device boot_props = {} for prop in properties: if prop in data: boot_props[prop] = data[prop] boot_options_dict[boot_option_ref] = boot_props return boot_options_dict def get_boot_order(self, systems_uri): result = {} # Retrieve System resource response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # Build boot device list boot_device_list = [] for ref in boot_order: boot_device_list.append( boot_options_dict.get(ref, {'BootOptionReference': ref})) result["entries"] = boot_device_list return result def get_multi_boot_order(self): return self.aggregate(self.get_boot_order) def get_boot_override(self, systems_uri): result = {} properties = ["BootSourceOverrideEnabled", "BootSourceOverrideTarget", "BootSourceOverrideMode", "UefiTargetBootSourceOverride", "[email protected]"] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Boot' not in data: return {'ret': False, 'msg': "Key Boot not found"} boot = data['Boot'] boot_overrides = {} if "BootSourceOverrideEnabled" in boot: if boot["BootSourceOverrideEnabled"] is not False: for property in properties: if property in boot: if boot[property] is not None: boot_overrides[property] = boot[property] else: return {'ret': False, 'msg': "No boot override is enabled."} result['entries'] = boot_overrides return result def get_multi_boot_override(self): return self.aggregate(self.get_boot_override) def set_bios_default_settings(self): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] reset_bios_settings_uri = data["Actions"]["#Bios.ResetBios"]["target"] response = self.post_request(self.root_uri + reset_bios_settings_uri, {}) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Set BIOS to default settings"} def set_one_time_boot_device(self, bootdevice, uefi_target, boot_next): result = {} key = "Boot" if not bootdevice: return {'ret': False, 'msg': "bootdevice option required for SetOneTimeBoot"} # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} boot = data[key] annotation = '[email protected]' if annotation in boot: allowable_values = boot[annotation] if isinstance(allowable_values, list) and bootdevice not in allowable_values: return {'ret': False, 'msg': "Boot device %s not in list of allowable values (%s)" % (bootdevice, allowable_values)} # read existing values enabled = boot.get('BootSourceOverrideEnabled') target = boot.get('BootSourceOverrideTarget') cur_uefi_target = boot.get('UefiTargetBootSourceOverride') cur_boot_next = boot.get('BootNext') if bootdevice == 'UefiTarget': if not uefi_target: return {'ret': False, 'msg': "uefi_target option required to SetOneTimeBoot for UefiTarget"} if enabled == 'Once' and target == bootdevice and uefi_target == cur_uefi_target: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'UefiTargetBootSourceOverride': uefi_target } } elif bootdevice == 'UefiBootNext': if not boot_next: return {'ret': False, 'msg': "boot_next option required to SetOneTimeBoot for UefiBootNext"} if enabled == 'Once' and target == bootdevice and boot_next == cur_boot_next: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice, 'BootNext': boot_next } } else: if enabled == 'Once' and target == bootdevice: # If properties are already set, no changes needed return {'ret': True, 'changed': False} payload = { 'Boot': { 'BootSourceOverrideEnabled': 'Once', 'BootSourceOverrideTarget': bootdevice } } response = self.patch_request(self.root_uri + self.systems_uris[0], payload) if response['ret'] is False: return response return {'ret': True, 'changed': True} def set_bios_attributes(self, attributes): result = {} key = "Bios" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] # Make a copy of the attributes dict attrs_to_patch = dict(attributes) # Check the attributes for attr in attributes: if attr not in data[u'Attributes']: return {'ret': False, 'msg': "BIOS attribute %s not found" % attr} # If already set to requested value, remove it from PATCH payload if data[u'Attributes'][attr] == attributes[attr]: del attrs_to_patch[attr] # Return success w/ changed=False if no attrs need to be changed if not attrs_to_patch: return {'ret': True, 'changed': False, 'msg': "BIOS attributes already set"} # Get the SettingsObject URI set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"]["@odata.id"] # Construct payload and issue PATCH command payload = {"Attributes": attrs_to_patch} response = self.patch_request(self.root_uri + set_bios_attr_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified BIOS attribute"} def set_boot_order(self, boot_list): if not boot_list: return {'ret': False, 'msg': "boot_order list required for SetBootOrder command"} # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # Confirm needed Boot properties are present if 'Boot' not in data or 'BootOrder' not in data['Boot']: return {'ret': False, 'msg': "Key BootOrder not found"} boot = data['Boot'] boot_order = boot['BootOrder'] boot_options_dict = self._get_boot_options_dict(boot) # validate boot_list against BootOptionReferences if available if boot_options_dict: boot_option_references = boot_options_dict.keys() for ref in boot_list: if ref not in boot_option_references: return {'ret': False, 'msg': "BootOptionReference %s not found in BootOptions" % ref} # If requested BootOrder is already set, nothing to do if boot_order == boot_list: return {'ret': True, 'changed': False, 'msg': "BootOrder already set to %s" % boot_list} payload = { 'Boot': { 'BootOrder': boot_list } } response = self.patch_request(self.root_uri + systems_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set"} def set_default_boot_order(self): # TODO(billdodd): change to self.systems_uri after PR 62921 merged systems_uri = self.systems_uris[0] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response data = response['data'] # get the #ComputerSystem.SetDefaultBootOrder Action and target URI action = '#ComputerSystem.SetDefaultBootOrder' if 'Actions' not in data or action not in data['Actions']: return {'ret': False, 'msg': 'Action %s not found' % action} if 'target' not in data['Actions'][action]: return {'ret': False, 'msg': 'target URI missing from Action %s' % action} action_uri = data['Actions'][action]['target'] # POST to Action URI payload = {} response = self.post_request(self.root_uri + action_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "BootOrder set to default"} def get_chassis_inventory(self): result = {} chassis_results = [] # Get these entries, but does not fail if not found properties = ['ChassisType', 'PartNumber', 'AssetTag', 'Manufacturer', 'IndicatorLED', 'SerialNumber', 'Model'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] chassis_result = {} for property in properties: if property in data: chassis_result[property] = data[property] chassis_results.append(chassis_result) result["entries"] = chassis_results return result def get_fan_inventory(self): result = {} fan_results = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['FanName', 'Reading', 'ReadingUnits', 'Status'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: # match: found an entry for "Thermal" information = fans thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for device in data[u'Fans']: fan = {} for property in properties: if property in device: fan[property] = device[property] fan_results.append(fan) result["entries"] = fan_results return result def get_chassis_power(self): result = {} key = "Power" # Get these entries, but does not fail if not found properties = ['Name', 'PowerAllocatedWatts', 'PowerAvailableWatts', 'PowerCapacityWatts', 'PowerConsumedWatts', 'PowerMetrics', 'PowerRequestedWatts', 'RelatedItem', 'Status'] chassis_power_results = [] # Go through list for chassis_uri in self.chassis_uri_list: chassis_power_result = {} response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: response = self.get_request(self.root_uri + data[key]['@odata.id']) data = response['data'] if 'PowerControl' in data: if len(data['PowerControl']) > 0: data = data['PowerControl'][0] for property in properties: if property in data: chassis_power_result[property] = data[property] else: return {'ret': False, 'msg': 'Key PowerControl not found.'} chassis_power_results.append(chassis_power_result) else: return {'ret': False, 'msg': 'Key Power not found.'} result['entries'] = chassis_power_results return result def get_chassis_thermals(self): result = {} sensors = [] key = "Thermal" # Get these entries, but does not fail if not found properties = ['Name', 'PhysicalContext', 'UpperThresholdCritical', 'UpperThresholdFatal', 'UpperThresholdNonCritical', 'LowerThresholdCritical', 'LowerThresholdFatal', 'LowerThresholdNonCritical', 'MaxReadingRangeTemp', 'MinReadingRangeTemp', 'ReadingCelsius', 'RelatedItem', 'SensorNumber'] # Go through list for chassis_uri in self.chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key in data: thermal_uri = data[key]["@odata.id"] response = self.get_request(self.root_uri + thermal_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if "Temperatures" in data: for sensor in data[u'Temperatures']: sensor_result = {} for property in properties: if property in sensor: if sensor[property] is not None: sensor_result[property] = sensor[property] sensors.append(sensor_result) if sensors is None: return {'ret': False, 'msg': 'Key Temperatures was not found.'} result['entries'] = sensors return result def get_cpu_inventory(self, systems_uri): result = {} cpu_list = [] cpu_results = [] key = "Processors" # Get these entries, but does not fail if not found properties = ['Id', 'Manufacturer', 'Model', 'MaxSpeedMHz', 'TotalCores', 'TotalThreads', 'Status'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} processors_uri = data[key]["@odata.id"] # Get a list of all CPUs and build respective URIs response = self.get_request(self.root_uri + processors_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for cpu in data[u'Members']: cpu_list.append(cpu[u'@odata.id']) for c in cpu_list: cpu = {} uri = self.root_uri + c response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: cpu[property] = data[property] cpu_results.append(cpu) result["entries"] = cpu_results return result def get_multi_cpu_inventory(self): return self.aggregate(self.get_cpu_inventory) def get_memory_inventory(self, systems_uri): result = {} memory_list = [] memory_results = [] key = "Memory" # Get these entries, but does not fail if not found properties = ['SerialNumber', 'MemoryDeviceType', 'PartNuber', 'MemoryLocation', 'RankCount', 'CapacityMiB', 'OperatingMemoryModes', 'Status', 'Manufacturer', 'Name'] # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} memory_uri = data[key]["@odata.id"] # Get a list of all DIMMs and build respective URIs response = self.get_request(self.root_uri + memory_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for dimm in data[u'Members']: memory_list.append(dimm[u'@odata.id']) for m in memory_list: dimm = {} uri = self.root_uri + m response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] if "Status" in data: if "State" in data["Status"]: if data["Status"]["State"] == "Absent": continue else: continue for property in properties: if property in data: dimm[property] = data[property] memory_results.append(dimm) result["entries"] = memory_results return result def get_multi_memory_inventory(self): return self.aggregate(self.get_memory_inventory) def get_nic_inventory(self, resource_uri): result = {} nic_list = [] nic_results = [] key = "EthernetInterfaces" # Get these entries, but does not fail if not found properties = ['Description', 'FQDN', 'IPv4Addresses', 'IPv6Addresses', 'NameServers', 'MACAddress', 'PermanentMACAddress', 'SpeedMbps', 'MTUSize', 'AutoNeg', 'Status'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} ethernetinterfaces_uri = data[key]["@odata.id"] # Get a list of all network controllers and build respective URIs response = self.get_request(self.root_uri + ethernetinterfaces_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for nic in data[u'Members']: nic_list.append(nic[u'@odata.id']) for n in nic_list: nic = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: nic[property] = data[property] nic_results.append(nic) result["entries"] = nic_results return result def get_multi_nic_inventory(self, resource_type): ret = True entries = [] # Given resource_type, use the proper URI if resource_type == 'Systems': resource_uris = self.systems_uris elif resource_type == 'Manager': # put in a list to match what we're doing with systems_uris resource_uris = [self.manager_uri] for resource_uri in resource_uris: inventory = self.get_nic_inventory(resource_uri) ret = inventory.pop('ret') and ret if 'entries' in inventory: entries.append(({'resource_uri': resource_uri}, inventory['entries'])) return dict(ret=ret, entries=entries) def get_virtualmedia(self, resource_uri): result = {} virtualmedia_list = [] virtualmedia_results = [] key = "VirtualMedia" # Get these entries, but does not fail if not found properties = ['Description', 'ConnectedVia', 'Id', 'MediaTypes', 'Image', 'ImageName', 'Name', 'WriteProtected', 'TransferMethod', 'TransferProtocolType'] response = self.get_request(self.root_uri + resource_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} virtualmedia_uri = data[key]["@odata.id"] # Get a list of all virtual media and build respective URIs response = self.get_request(self.root_uri + virtualmedia_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for virtualmedia in data[u'Members']: virtualmedia_list.append(virtualmedia[u'@odata.id']) for n in virtualmedia_list: virtualmedia = {} uri = self.root_uri + n response = self.get_request(uri) if response['ret'] is False: return response data = response['data'] for property in properties: if property in data: virtualmedia[property] = data[property] virtualmedia_results.append(virtualmedia) result["entries"] = virtualmedia_results return result def get_multi_virtualmedia(self): ret = True entries = [] # Because _find_managers_resource() only find last Manager uri in self.manager_uri, not one list. This should be 1 issue. # I have to put manager_uri into list to reduce future changes when the issue is fixed. resource_uris = [self.manager_uri] for resource_uri in resource_uris: virtualmedia = self.get_virtualmedia(resource_uri) ret = virtualmedia.pop('ret') and ret if 'entries' in virtualmedia: entries.append(({'resource_uri': resource_uri}, virtualmedia['entries'])) return dict(ret=ret, entries=entries) def get_psu_inventory(self): result = {} psu_list = [] psu_results = [] key = "PowerSupplies" # Get these entries, but does not fail if not found properties = ['Name', 'Model', 'SerialNumber', 'PartNumber', 'Manufacturer', 'FirmwareVersion', 'PowerCapacityWatts', 'PowerSupplyType', 'Status'] # Get a list of all Chassis and build URIs, then get all PowerSupplies # from each Power entry in the Chassis chassis_uri_list = self.chassis_uri_list for chassis_uri in chassis_uri_list: response = self.get_request(self.root_uri + chassis_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] if 'Power' in data: power_uri = data[u'Power'][u'@odata.id'] else: continue response = self.get_request(self.root_uri + power_uri) data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} psu_list = data[key] for psu in psu_list: psu_not_present = False psu_data = {} for property in properties: if property in psu: if psu[property] is not None: if property == 'Status': if 'State' in psu[property]: if psu[property]['State'] == 'Absent': psu_not_present = True psu_data[property] = psu[property] if psu_not_present: continue psu_results.append(psu_data) result["entries"] = psu_results if not result["entries"]: return {'ret': False, 'msg': "No PowerSupply objects found"} return result def get_multi_psu_inventory(self): return self.aggregate(self.get_psu_inventory) def get_system_inventory(self, systems_uri): result = {} inventory = {} # Get these entries, but does not fail if not found properties = ['Status', 'HostName', 'PowerState', 'Model', 'Manufacturer', 'PartNumber', 'SystemType', 'AssetTag', 'ServiceTag', 'SerialNumber', 'SKU', 'BiosVersion', 'MemorySummary', 'ProcessorSummary', 'TrustedModules'] response = self.get_request(self.root_uri + systems_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] for property in properties: if property in data: inventory[property] = data[property] result["entries"] = inventory return result def get_multi_system_inventory(self): return self.aggregate(self.get_system_inventory) def get_network_protocols(self): result = {} service_result = {} # Find NetworkProtocol response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'NetworkProtocol' not in data: return {'ret': False, 'msg': "NetworkProtocol resource not found"} networkprotocol_uri = data["NetworkProtocol"]["@odata.id"] response = self.get_request(self.root_uri + networkprotocol_uri) if response['ret'] is False: return response data = response['data'] protocol_services = ['SNMP', 'VirtualMedia', 'Telnet', 'SSDP', 'IPMI', 'SSH', 'KVMIP', 'NTP', 'HTTP', 'HTTPS', 'DHCP', 'DHCPv6', 'RDP', 'RFB'] for protocol_service in protocol_services: if protocol_service in data.keys(): service_result[protocol_service] = data[protocol_service] result['ret'] = True result["entries"] = service_result return result def set_network_protocols(self, manager_services): # Check input data validity protocol_services = ['SNMP', 'VirtualMedia', 'Telnet', 'SSDP', 'IPMI', 'SSH', 'KVMIP', 'NTP', 'HTTP', 'HTTPS', 'DHCP', 'DHCPv6', 'RDP', 'RFB'] protocol_state_onlist = ['true', 'True', True, 'on', 1] protocol_state_offlist = ['false', 'False', False, 'off', 0] payload = {} for service_name in manager_services.keys(): if service_name not in protocol_services: return {'ret': False, 'msg': "Service name %s is invalid" % service_name} payload[service_name] = {} for service_property in manager_services[service_name].keys(): value = manager_services[service_name][service_property] if service_property in ['ProtocolEnabled', 'protocolenabled']: if value in protocol_state_onlist: payload[service_name]['ProtocolEnabled'] = True elif value in protocol_state_offlist: payload[service_name]['ProtocolEnabled'] = False else: return {'ret': False, 'msg': "Value of property %s is invalid" % service_property} elif service_property in ['port', 'Port']: if isinstance(value, int): payload[service_name]['Port'] = value elif isinstance(value, str) and value.isdigit(): payload[service_name]['Port'] = int(value) else: return {'ret': False, 'msg': "Value of property %s is invalid" % service_property} else: payload[service_name][service_property] = value # Find NetworkProtocol response = self.get_request(self.root_uri + self.manager_uri) if response['ret'] is False: return response data = response['data'] if 'NetworkProtocol' not in data: return {'ret': False, 'msg': "NetworkProtocol resource not found"} networkprotocol_uri = data["NetworkProtocol"]["@odata.id"] # Check service property support or not response = self.get_request(self.root_uri + networkprotocol_uri) if response['ret'] is False: return response data = response['data'] for service_name in payload.keys(): if service_name not in data: return {'ret': False, 'msg': "%s service not supported" % service_name} for service_property in payload[service_name].keys(): if service_property not in data[service_name]: return {'ret': False, 'msg': "%s property for %s service not supported" % (service_property, service_name)} # if the protocol is already set, nothing to do need_change = False for service_name in payload.keys(): for service_property in payload[service_name].keys(): value = payload[service_name][service_property] if value != data[service_name][service_property]: need_change = True break if not need_change: return {'ret': True, 'changed': False, 'msg': "Manager NetworkProtocol services already set"} response = self.patch_request(self.root_uri + networkprotocol_uri, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified Manager NetworkProtocol services"}
closed
ansible/ansible
https://github.com/ansible/ansible
58,467
Redfish commands need way to specify single system, manager or chassis
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> A number of the existing Redfish commands act on a single system, manager or chassis. But there is no option to specify which one to act on if there are multiple systems, managers or chassis in the service. Currently, in this case, the module will act on the first one in the collection. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_utils.py redfish_config.py redfish_command.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Given the issue summarized above, it is impossible to issue certain commands to systems, managers and chassis beyond the first one that appears in the collection. To solve this, the behavior will be updated as follows: - New options to specify a particular system, manager or chassis will be added. - For the impacted commands (see below), if there is exactly one system/manager/chassis resource in the service, act on that resource. Specifying the system/manager/chassis using the new options will not be required. - In the case where there are multiple system/manager/chassis resources, the one to act on ~~must~~ should be specified using the new options. If one is not specified, ~~an error~~ a deprecation warning will be reported and ~~no action taken~~ the existing behavior of using the first resource in the collection will be used. Here are the impacted commands. Commands that act on a single **system**: - Power* (PowerOn, PowerReboot, etc.) - SetOneTimeBoot - SetBiosDefaultSettings - SetBiosAttributes Commands that act on a single **manager**: - GracefulRestart - ClearLogs Commands that act on a single **chassis**: - IndicatorLedOn, IndicatorLedOff, IndicatorLedBlink <!--- Paste example playbooks or commands between quotes below --> An example of an existing playbook to reboot a system: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` An example of the playbook after adding a new option to specify the system to reboot: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot system_id: 437XR1138R2 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` **Note:** When implementing this feature, but sure to fix any places that may result in errors like: `The value Lit for the property IndicatorLED is not in the list of acceptable values` `Key IndicatorLED not found` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/58467
https://github.com/ansible/ansible/pull/62921
c3838b5d7340e0b6e2abae3fc17a38092fddff71
4349ab57779679d273a61cff88347a5416fac05e
2019-06-27T16:05:09Z
python
2019-10-31T22:09:48Z
lib/ansible/modules/remote_management/redfish/idrac_redfish_command.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: idrac_redfish_command version_added: "2.8" short_description: Manages Out-Of-Band controllers using iDRAC OEM Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to perform an action. - For use with Dell iDRAC operations that require Redfish OEM extensions options: category: required: true description: - Category to execute on OOB controller type: str command: required: true description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - User for authentication with OOB controller type: str password: required: true description: - Password for authentication with OOB controller type: str timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: '2.8' author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Create BIOS configuration job (schedule BIOS setting update) idrac_redfish_command: category: Systems command: CreateBiosConfigJob baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' import re from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native class IdracRedfishUtils(RedfishUtils): def create_bios_config_job(self): result = {} key = "Bios" jobs = "Jobs" # Search for 'key' entry and extract URI from it response = self.get_request(self.root_uri + self.systems_uris[0]) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} bios_uri = data[key]["@odata.id"] # Extract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"][ "@odata.id"] payload = {"TargetSettingsURI": set_bios_attr_uri} response = self.post_request( self.root_uri + self.manager_uri + "/" + jobs, payload) if response['ret'] is False: return response response_output = response['resp'].__dict__ job_id = response_output["headers"]["Location"] job_id = re.search("JID_.+", job_id).group() # Currently not passing job_id back to user but patch is coming return {'ret': True, 'msg': "Config job %s created" % job_id} CATEGORY_COMMANDS_ALL = { "Systems": ["CreateBiosConfigJob"], "Accounts": [], "Manager": [] } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), timeout=dict(type='int', default=10) ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = IdracRedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "CreateBiosConfigJob": # execute only if we find a Managers resource result = rf_utils._find_managers_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) result = rf_utils.create_bios_config_job() # Return data back or fail with proper message if result['ret'] is True: del result['ret'] module.exit_json(changed=True, msg='Action was successful') else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
58,467
Redfish commands need way to specify single system, manager or chassis
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> A number of the existing Redfish commands act on a single system, manager or chassis. But there is no option to specify which one to act on if there are multiple systems, managers or chassis in the service. Currently, in this case, the module will act on the first one in the collection. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_utils.py redfish_config.py redfish_command.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Given the issue summarized above, it is impossible to issue certain commands to systems, managers and chassis beyond the first one that appears in the collection. To solve this, the behavior will be updated as follows: - New options to specify a particular system, manager or chassis will be added. - For the impacted commands (see below), if there is exactly one system/manager/chassis resource in the service, act on that resource. Specifying the system/manager/chassis using the new options will not be required. - In the case where there are multiple system/manager/chassis resources, the one to act on ~~must~~ should be specified using the new options. If one is not specified, ~~an error~~ a deprecation warning will be reported and ~~no action taken~~ the existing behavior of using the first resource in the collection will be used. Here are the impacted commands. Commands that act on a single **system**: - Power* (PowerOn, PowerReboot, etc.) - SetOneTimeBoot - SetBiosDefaultSettings - SetBiosAttributes Commands that act on a single **manager**: - GracefulRestart - ClearLogs Commands that act on a single **chassis**: - IndicatorLedOn, IndicatorLedOff, IndicatorLedBlink <!--- Paste example playbooks or commands between quotes below --> An example of an existing playbook to reboot a system: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` An example of the playbook after adding a new option to specify the system to reboot: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot system_id: 437XR1138R2 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` **Note:** When implementing this feature, but sure to fix any places that may result in errors like: `The value Lit for the property IndicatorLED is not in the list of acceptable values` `Key IndicatorLED not found` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/58467
https://github.com/ansible/ansible/pull/62921
c3838b5d7340e0b6e2abae3fc17a38092fddff71
4349ab57779679d273a61cff88347a5416fac05e
2019-06-27T16:05:09Z
python
2019-10-31T22:09:48Z
lib/ansible/modules/remote_management/redfish/idrac_redfish_config.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2019 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: idrac_redfish_config version_added: '2.8' short_description: Manages servers through iDRAC using Dell Redfish APIs description: - For use with Dell iDRAC operations that require Redfish OEM extensions - Builds Redfish URIs locally and sends them to remote iDRAC controllers to set or update a configuration attribute. options: category: required: true type: str description: - Category to execute on iDRAC command: required: true description: - List of commands to execute on iDRAC type: list baseuri: required: true description: - Base URI of iDRAC type: str username: required: true description: - User for authentication with iDRAC type: str password: required: true description: - Password for authentication with iDRAC type: str manager_attribute_name: required: false description: - name of iDRAC attribute to update default: 'null' type: str manager_attribute_value: required: false description: - value of iDRAC attribute to update default: 'null' type: str timeout: description: - Timeout in seconds for URL requests to iDRAC controller default: 10 type: int author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Enable NTP in iDRAC idrac_redfish_config: category: Manager command: SetManagerAttributes manager_attribute_name: NTPConfigGroup.1.NTPEnable manager_attribute_value: Enabled baseuri: "{{ baseuri }}" username: "{{ username}}" password: "{{ password }}" - name: Set NTP server 1 to {{ ntpserver1 }} in iDRAC idrac_redfish_config: category: Manager command: SetManagerAttributes manager_attribute_name: NTPConfigGroup.1.NTP1 manager_attribute_value: "{{ ntpserver1 }}" baseuri: "{{ baseuri }}" username: "{{ username}}" password: "{{ password }}" - name: Set Timezone to {{ timezone }} in iDRAC idrac_redfish_config: category: Manager command: SetManagerAttributes manager_attribute_name: Time.1.Timezone manager_attribute_value: "{{ timezone }}" baseuri: "{{ baseuri }}" username: "{{ username}}" password: "{{ password }}" ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native class IdracRedfishUtils(RedfishUtils): def set_manager_attributes(self, attr): result = {} # Here I'm making the assumption that the key 'Attributes' is part of the URI. # It may not, but in the hardware I tested with, getting to the final URI where # the Manager Attributes are, appear to be part of a specific OEM extension. key = "Attributes" # Search for key entry and extract URI from it response = self.get_request(self.root_uri + self.manager_uri + "/" + key) if response['ret'] is False: return response result['ret'] = True data = response['data'] if key not in data: return {'ret': False, 'msg': "Key %s not found" % key} # Check if attribute exists if attr['mgr_attr_name'] not in data[key]: return {'ret': False, 'msg': "Manager attribute %s not found" % attr['mgr_attr_name']} # Example: manager_attr = {\"name\":\"value\"} # Check if value is a number. If so, convert to int. if attr['mgr_attr_value'].isdigit(): manager_attr = "{\"%s\": %i}" % (attr['mgr_attr_name'], int(attr['mgr_attr_value'])) else: manager_attr = "{\"%s\": \"%s\"}" % (attr['mgr_attr_name'], attr['mgr_attr_value']) # Find out if value is already set to what we want. If yes, return if data[key][attr['mgr_attr_name']] == attr['mgr_attr_value']: return {'ret': True, 'changed': False, 'msg': "Manager attribute already set"} payload = {"Attributes": json.loads(manager_attr)} response = self.patch_request(self.root_uri + self.manager_uri + "/" + key, payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, 'msg': "Modified Manager attribute %s" % attr['mgr_attr_name']} CATEGORY_COMMANDS_ALL = { "Manager": ["SetManagerAttributes"] } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), manager_attribute_name=dict(default='null'), manager_attribute_value=dict(default='null'), timeout=dict(type='int', default=10) ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # iDRAC attributes to update mgr_attributes = {'mgr_attr_name': module.params['manager_attribute_name'], 'mgr_attr_value': module.params['manager_attribute_value']} # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = IdracRedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Manager": # execute only if we find a Manager resource result = rf_utils._find_managers_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetManagerAttributes": result = rf_utils.set_manager_attributes(mgr_attributes) # Return data back or fail with proper message if result['ret'] is True: module.exit_json(changed=result['changed'], msg=to_native(result['msg'])) else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
58,467
Redfish commands need way to specify single system, manager or chassis
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> A number of the existing Redfish commands act on a single system, manager or chassis. But there is no option to specify which one to act on if there are multiple systems, managers or chassis in the service. Currently, in this case, the module will act on the first one in the collection. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_utils.py redfish_config.py redfish_command.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Given the issue summarized above, it is impossible to issue certain commands to systems, managers and chassis beyond the first one that appears in the collection. To solve this, the behavior will be updated as follows: - New options to specify a particular system, manager or chassis will be added. - For the impacted commands (see below), if there is exactly one system/manager/chassis resource in the service, act on that resource. Specifying the system/manager/chassis using the new options will not be required. - In the case where there are multiple system/manager/chassis resources, the one to act on ~~must~~ should be specified using the new options. If one is not specified, ~~an error~~ a deprecation warning will be reported and ~~no action taken~~ the existing behavior of using the first resource in the collection will be used. Here are the impacted commands. Commands that act on a single **system**: - Power* (PowerOn, PowerReboot, etc.) - SetOneTimeBoot - SetBiosDefaultSettings - SetBiosAttributes Commands that act on a single **manager**: - GracefulRestart - ClearLogs Commands that act on a single **chassis**: - IndicatorLedOn, IndicatorLedOff, IndicatorLedBlink <!--- Paste example playbooks or commands between quotes below --> An example of an existing playbook to reboot a system: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` An example of the playbook after adding a new option to specify the system to reboot: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot system_id: 437XR1138R2 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` **Note:** When implementing this feature, but sure to fix any places that may result in errors like: `The value Lit for the property IndicatorLED is not in the list of acceptable values` `Key IndicatorLED not found` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/58467
https://github.com/ansible/ansible/pull/62921
c3838b5d7340e0b6e2abae3fc17a38092fddff71
4349ab57779679d273a61cff88347a5416fac05e
2019-06-27T16:05:09Z
python
2019-10-31T22:09:48Z
lib/ansible/modules/remote_management/redfish/redfish_command.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_command version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to perform an action. - Manages OOB controller ex. reboot, log management. - Manages OOB controller users ex. add, remove, update. - Manages system power ex. on, off, graceful and forced reboot. options: category: required: true description: - Category to execute on OOB controller type: str command: required: true description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - Username for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str id: required: false aliases: [ account_id ] description: - ID of account to delete/modify type: str version_added: "2.8" new_username: required: false aliases: [ account_username ] description: - Username of account to add/delete/modify type: str version_added: "2.8" new_password: required: false aliases: [ account_password ] description: - New password of account to add/modify type: str version_added: "2.8" roleid: required: false aliases: [ account_roleid ] description: - Role of account to add/modify type: str version_added: "2.8" bootdevice: required: false description: - bootdevice when setting boot configuration type: str timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: '2.8' uefi_target: required: false description: - UEFI target when bootdevice is "UefiTarget" type: str version_added: "2.9" boot_next: required: false description: - BootNext target when bootdevice is "UefiBootNext" type: str version_added: "2.9" update_username: required: false aliases: [ account_updatename ] description: - new update user name for account_username type: str version_added: "2.10" account_properties: required: false description: - properties of account service to update type: dict version_added: "2.10" author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Restart system power gracefully redfish_command: category: Systems command: PowerGracefulRestart baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set one-time boot device to {{ bootdevice }} redfish_command: category: Systems command: SetOneTimeBoot bootdevice: "{{ bootdevice }}" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set one-time boot device to UefiTarget of "/0x31/0x33/0x01/0x01" redfish_command: category: Systems command: SetOneTimeBoot bootdevice: "UefiTarget" uefi_target: "/0x31/0x33/0x01/0x01" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set one-time boot device to BootNext target of "Boot0001" redfish_command: category: Systems command: SetOneTimeBoot bootdevice: "UefiBootNext" boot_next: "Boot0001" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set chassis indicator LED to blink redfish_command: category: Chassis command: IndicatorLedBlink baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Add user redfish_command: category: Accounts command: AddUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" new_username: "{{ new_username }}" new_password: "{{ new_password }}" roleid: "{{ roleid }}" - name: Add user using new option aliases redfish_command: category: Accounts command: AddUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" account_password: "{{ account_password }}" account_roleid: "{{ account_roleid }}" - name: Delete user redfish_command: category: Accounts command: DeleteUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" - name: Disable user redfish_command: category: Accounts command: DisableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" - name: Enable user redfish_command: category: Accounts command: EnableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" - name: Add and enable user redfish_command: category: Accounts command: AddUser,EnableUser baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" new_username: "{{ new_username }}" new_password: "{{ new_password }}" roleid: "{{ roleid }}" - name: Update user password redfish_command: category: Accounts command: UpdateUserPassword baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" account_password: "{{ account_password }}" - name: Update user role redfish_command: category: Accounts command: UpdateUserRole baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" roleid: "{{ roleid }}" - name: Update user name redfish_command: category: Accounts command: UpdateUserName baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" account_updatename: "{{ account_updatename }}" - name: Update user name redfish_command: category: Accounts command: UpdateUserName baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_username: "{{ account_username }}" update_username: "{{ update_username }}" - name: Update AccountService properties redfish_command: category: Accounts command: UpdateAccountServiceProperties baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" account_properties: AccountLockoutThreshold: 5 AccountLockoutDuration: 600 - name: Clear Manager Logs with a timeout of 20 seconds redfish_command: category: Manager command: ClearLogs baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native # More will be added as module features are expanded CATEGORY_COMMANDS_ALL = { "Systems": ["PowerOn", "PowerForceOff", "PowerForceRestart", "PowerGracefulRestart", "PowerGracefulShutdown", "PowerReboot", "SetOneTimeBoot"], "Chassis": ["IndicatorLedOn", "IndicatorLedOff", "IndicatorLedBlink"], "Accounts": ["AddUser", "EnableUser", "DeleteUser", "DisableUser", "UpdateUserRole", "UpdateUserPassword", "UpdateUserName", "UpdateAccountServiceProperties"], "Manager": ["GracefulRestart", "ClearLogs"], } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), id=dict(aliases=["account_id"]), new_username=dict(aliases=["account_username"]), new_password=dict(aliases=["account_password"], no_log=True), roleid=dict(aliases=["account_roleid"]), update_username=dict(type='str', aliases=["account_updatename"]), account_properties=dict(type='dict', default={}), bootdevice=dict(), timeout=dict(type='int', default=10), uefi_target=dict(), boot_next=dict() ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # user to add/modify/delete user = {'account_id': module.params['id'], 'account_username': module.params['new_username'], 'account_password': module.params['new_password'], 'account_roleid': module.params['roleid'], 'account_updatename': module.params['update_username'], 'account_properties': module.params['account_properties']} # timeout timeout = module.params['timeout'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Accounts": ACCOUNTS_COMMANDS = { "AddUser": rf_utils.add_user, "EnableUser": rf_utils.enable_user, "DeleteUser": rf_utils.delete_user, "DisableUser": rf_utils.disable_user, "UpdateUserRole": rf_utils.update_user_role, "UpdateUserPassword": rf_utils.update_user_password, "UpdateUserName": rf_utils.update_user_name, "UpdateAccountServiceProperties": rf_utils.update_accountservice_properties } # execute only if we find an Account service resource result = rf_utils._find_accountservice_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: result = ACCOUNTS_COMMANDS[command](user) elif category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if "Power" in command: result = rf_utils.manage_system_power(command) elif command == "SetOneTimeBoot": result = rf_utils.set_one_time_boot_device( module.params['bootdevice'], module.params['uefi_target'], module.params['boot_next']) elif category == "Chassis": result = rf_utils._find_chassis_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) led_commands = ["IndicatorLedOn", "IndicatorLedOff", "IndicatorLedBlink"] # Check if more than one led_command is present num_led_commands = sum([command in led_commands for command in command_list]) if num_led_commands > 1: result = {'ret': False, 'msg': "Only one IndicatorLed command should be sent at a time."} else: for command in command_list: if command in led_commands: result = rf_utils.manage_indicator_led(command) elif category == "Manager": MANAGER_COMMANDS = { "GracefulRestart": rf_utils.restart_manager_gracefully, "ClearLogs": rf_utils.clear_logs } # execute only if we find a Manager service resource result = rf_utils._find_managers_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: result = MANAGER_COMMANDS[command]() # Return data back or fail with proper message if result['ret'] is True: del result['ret'] changed = result.get('changed', True) module.exit_json(changed=changed, msg='Action was successful') else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
58,467
Redfish commands need way to specify single system, manager or chassis
<!--- Verify first that your feature was not already discussed on GitHub --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Describe the new feature/improvement briefly below --> A number of the existing Redfish commands act on a single system, manager or chassis. But there is no option to specify which one to act on if there are multiple systems, managers or chassis in the service. Currently, in this case, the module will act on the first one in the collection. ##### ISSUE TYPE - Feature Idea ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> redfish_utils.py redfish_config.py redfish_command.py ##### ADDITIONAL INFORMATION <!--- Describe how the feature would be used, why it is needed and what it would solve --> Given the issue summarized above, it is impossible to issue certain commands to systems, managers and chassis beyond the first one that appears in the collection. To solve this, the behavior will be updated as follows: - New options to specify a particular system, manager or chassis will be added. - For the impacted commands (see below), if there is exactly one system/manager/chassis resource in the service, act on that resource. Specifying the system/manager/chassis using the new options will not be required. - In the case where there are multiple system/manager/chassis resources, the one to act on ~~must~~ should be specified using the new options. If one is not specified, ~~an error~~ a deprecation warning will be reported and ~~no action taken~~ the existing behavior of using the first resource in the collection will be used. Here are the impacted commands. Commands that act on a single **system**: - Power* (PowerOn, PowerReboot, etc.) - SetOneTimeBoot - SetBiosDefaultSettings - SetBiosAttributes Commands that act on a single **manager**: - GracefulRestart - ClearLogs Commands that act on a single **chassis**: - IndicatorLedOn, IndicatorLedOff, IndicatorLedBlink <!--- Paste example playbooks or commands between quotes below --> An example of an existing playbook to reboot a system: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` An example of the playbook after adding a new option to specify the system to reboot: ```yaml - name: Reboot system power redfish_command: category: Systems command: PowerReboot system_id: 437XR1138R2 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ``` **Note:** When implementing this feature, but sure to fix any places that may result in errors like: `The value Lit for the property IndicatorLED is not in the list of acceptable values` `Key IndicatorLED not found` <!--- HINT: You can also paste gist.github.com links for larger files -->
https://github.com/ansible/ansible/issues/58467
https://github.com/ansible/ansible/pull/62921
c3838b5d7340e0b6e2abae3fc17a38092fddff71
4349ab57779679d273a61cff88347a5416fac05e
2019-06-27T16:05:09Z
python
2019-10-31T22:09:48Z
lib/ansible/modules/remote_management/redfish/redfish_config.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017-2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: redfish_config version_added: "2.7" short_description: Manages Out-Of-Band controllers using Redfish APIs description: - Builds Redfish URIs locally and sends them to remote OOB controllers to set or update a configuration attribute. - Manages BIOS configuration settings. - Manages OOB controller configuration settings. options: category: required: true description: - Category to execute on OOB controller type: str command: required: true description: - List of commands to execute on OOB controller type: list baseuri: required: true description: - Base URI of OOB controller type: str username: required: true description: - User for authentication with OOB controller type: str version_added: "2.8" password: required: true description: - Password for authentication with OOB controller type: str bios_attribute_name: required: false description: - name of BIOS attr to update (deprecated - use bios_attributes instead) default: 'null' type: str version_added: "2.8" bios_attribute_value: required: false description: - value of BIOS attr to update (deprecated - use bios_attributes instead) default: 'null' type: str version_added: "2.8" bios_attributes: required: false description: - dictionary of BIOS attributes to update default: {} type: dict version_added: "2.10" timeout: description: - Timeout in seconds for URL requests to OOB controller default: 10 type: int version_added: "2.8" boot_order: required: false description: - list of BootOptionReference strings specifying the BootOrder default: [] type: list version_added: "2.10" network_protocols: required: false description: - setting dict of manager services to update type: dict version_added: "2.10" author: "Jose Delarosa (@jose-delarosa)" ''' EXAMPLES = ''' - name: Set BootMode to UEFI redfish_config: category: Systems command: SetBiosAttributes bios_attributes: BootMode: "Uefi" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set multiple BootMode attributes redfish_config: category: Systems command: SetBiosAttributes bios_attributes: BootMode: "Bios" OneTimeBootMode: "Enabled" BootSeqRetry: "Enabled" baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Enable PXE Boot for NIC1 using deprecated options redfish_config: category: Systems command: SetBiosAttributes bios_attribute_name: PxeDev1EnDis bios_attribute_value: Enabled baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set BIOS default settings with a timeout of 20 seconds redfish_config: category: Systems command: SetBiosDefaultSettings baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" timeout: 20 - name: Set boot order redfish_config: category: Systems command: SetBootOrder boot_order: - Boot0002 - Boot0001 - Boot0000 - Boot0003 - Boot0004 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set boot order to the default redfish_config: category: Systems command: SetDefaultBootOrder baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" - name: Set Manager Network Protocols redfish_config: category: Manager command: SetNetworkProtocols network_protocols: SNMP: ProtocolEnabled: True Port: 161 HTTP: ProtocolEnabled: False Port: 8080 baseuri: "{{ baseuri }}" username: "{{ username }}" password: "{{ password }}" ''' RETURN = ''' msg: description: Message with action result or error description returned: always type: str sample: "Action was successful" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.redfish_utils import RedfishUtils from ansible.module_utils._text import to_native # More will be added as module features are expanded CATEGORY_COMMANDS_ALL = { "Systems": ["SetBiosDefaultSettings", "SetBiosAttributes", "SetBootOrder", "SetDefaultBootOrder"], "Manager": ["SetNetworkProtocols"] } def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), bios_attribute_name=dict(default='null'), bios_attribute_value=dict(default='null'), bios_attributes=dict(type='dict', default={}), timeout=dict(type='int', default=10), boot_order=dict(type='list', elements='str', default=[]), network_protocols=dict( type='dict', default={} ) ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # BIOS attributes to update bios_attributes = module.params['bios_attributes'] if module.params['bios_attribute_name'] != 'null': bios_attributes[module.params['bios_attribute_name']] = module.params[ 'bios_attribute_value'] module.deprecate(msg='The bios_attribute_name/bios_attribute_value ' 'options are deprecated. Use bios_attributes instead', version='2.10') # boot order boot_order = module.params['boot_order'] # Build root URI root_uri = "https://" + module.params['baseuri'] rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetBiosDefaultSettings": result = rf_utils.set_bios_default_settings() elif command == "SetBiosAttributes": result = rf_utils.set_bios_attributes(bios_attributes) elif command == "SetBootOrder": result = rf_utils.set_boot_order(boot_order) elif command == "SetDefaultBootOrder": result = rf_utils.set_default_boot_order() elif category == "Manager": # execute only if we find a Manager service resource result = rf_utils._find_managers_resource() if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetNetworkProtocols": result = rf_utils.set_network_protocols(module.params['network_protocols']) # Return data back or fail with proper message if result['ret'] is True: module.exit_json(changed=result['changed'], msg=to_native(result['msg'])) else: module.fail_json(msg=to_native(result['msg'])) if __name__ == '__main__': main()
closed
ansible/ansible
https://github.com/ansible/ansible
64,275
ansible-test partially included in ansible rpm
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When installing the Ansible 2.9 (or the nightly 2.10) rpm, it installs `/usr/bin/ansible-test` but none of the `ansible_test` libraries. Running `ansible-test` produces a stack trace as a result. This may be due to the glob in the spec file picking up `ansible-test`, but I'm not sure. https://github.com/ansible/ansible/blob/c76e074e4c71c7621a1ca8159261c1959b5287af/packaging/rpm/ansible.spec#L286 ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> `packaging/rpm/ansible.spec` ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below 2.9 2.10 ``` ##### CONFIGURATION Default ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> CentOS 8 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> Install _only_ `ansible` and try to run `ansible-test`. <!--- Paste example playbooks or commands between quotes below --> ``` # dnf install ansible # ansible-test --version ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> Installing `ansible` will not install `ansible-test`. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> <!--- Paste verbatim command output between quotes --> ```paste below # ansible-test --help Traceback (most recent call last): File "/usr/bin/ansible-test", line 28, in <module> main() File "/usr/bin/ansible-test", line 22, in main from ansible_test._internal.cli import main as cli_main ModuleNotFoundError: No module named 'ansible_test' ``` Also, `/usr/bin/ansible-test` is owned by two packages, which may cause issues when updating. ``` # rpm -qf /usr/bin/ansible-test ansible-2.10.0-1.201910291726git.c782831dd7.el8.ans.noarch ansible-test-2.10.0-1.201910291726git.c782831dd7.el8.ans.noarch ```
https://github.com/ansible/ansible/issues/64275
https://github.com/ansible/ansible/pull/64277
c76e074e4c71c7621a1ca8159261c1959b5287af
87de14603891f4e61854300e090598e4f80b7376
2019-11-01T15:16:27Z
python
2019-11-01T16:14:36Z
packaging/rpm/ansible.spec
%define release_date %(date "+%a %b %e %Y") # Disable shebang munging for specific paths. These files are data files. # ansible-test munges the shebangs itself. %global __brp_mangle_shebangs_exclude_from /usr/lib/python[0-9]+\.[0-9]+/site-packages/ansible_test/_data/.* # RHEL and Fedora add -s to the shebang line. We do *not* use -s -E -S or -I # with ansible because it has many optional features which users need to # install libraries on their own to use. For instance, paramiko for the # network connection plugins or winrm to talk to windows hosts. # Set this to nil to remove -s %define py_shbang_opts %{nil} %define py2_shbang_opts %{nil} %define py3_shbang_opts %{nil} %if 0%{?fedora} || 0%{?rhel} >= 8 %global with_python2 0 %global with_python3 1 %else %global with_python2 1 %global with_python3 0 %endif Name: ansible Summary: SSH-based configuration management, deployment, and task execution system Version: %{rpmversion} Release: %{rpmrelease}%{?dist}%{?repotag} Group: Development/Libraries License: GPLv3+ Source0: https://releases.ansible.com/ansible/%{name}-%{upstream_version}.tar.gz Url: http://ansible.com BuildArch: noarch BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot %{!?python2_sitelib: %global python_sitelib %(%{__python2} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")} %{!?python3_sitelib: %global python_sitelib %(%{__python3} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")} # Bundled provides Provides: bundled(python-backports-ssl_match_hostname) = 3.7.0.1 Provides: bundled(python-distro) = 1.4.0 Provides: bundled(python-ipaddress) = 1.0.22 Provides: bundled(python-selectors2) = 1.1.1 Provides: bundled(python-six) = 1.12.0 %if 0%{?rhel} >= 8 BuildRequires: python3-devel BuildRequires: python3-setuptools # man pages BuildRequires: python3-docutils # Tests BuildRequires: python3-jinja2 BuildRequires: python3-PyYAML BuildRequires: python3-cryptography BuildRequires: python3-six BuildRequires: python3-pytest BuildRequires: python3-pytest-xdist BuildRequires: python3-pytest-mock BuildRequires: python3-requests BUildRequires: %{py3_dist coverage} BuildRequires: python3-mock # Not available in RHEL8, we'll just skip the tests where they apply #BuildRequires: python3-boto3 #BuildRequires: python3-botocore BuildRequires: python3-systemd BuildRequires: git-core Requires: python3-jinja2 Requires: python3-PyYAML Requires: python3-cryptography Requires: python3-six Requires: sshpass %else %if 0%{?rhel} >= 7 # RHEL 7 BuildRequires: python2-devel BuildRequires: python-setuptools # For building docs BuildRequires: python-sphinx # Tests BuildRequires: python-jinja2 BuildRequires: PyYAML BuildRequires: python2-cryptography BuildRequires: python-six # rhel7 does not have python-pytest but has pytest BuildRequires: pytest #BuildRequires: python-pytest-xdist #BuildRequires: python-pytest-mock BuildRequires: python-requests BuildRequires: python-coverage BuildRequires: python-mock BuildRequires: python-boto3 #BuildRequires: python-botocore BuildRequires: git BuildRequires: python-paramiko BuildRequires: python-jmespath BuildRequires: python-passlib Requires: python-jinja2 Requires: PyYAML Requires: python2-cryptography Requires: python-six Requires: sshpass # As of Ansible-2.9.0, we no longer depend on the optional dependencies jmespath or passlib # Users have to install those on their own Requires: python-paramiko # The ansible-doc package is no longer provided as of Ansible Engine 2.6.0 Obsoletes: ansible-doc < 2.6.0 %endif # Requires for RHEL 7 %endif # Requires for RHEL 8 # FEDORA >= 29 %if 0%{?fedora} >= 29 BuildRequires: python3-devel BuildRequires: python3-setuptools Requires: python3-PyYAML Requires: python3-paramiko Requires: python3-jinja2 Requires: python3-httplib2 Requires: python3-setuptools Requires: python3-six Requires: sshpass %endif # SUSE/openSUSE %if 0%{?suse_version} BuildRequires: python-devel BuildRequires: python-setuptools Requires: python-paramiko Requires: python-jinja2 Requires: python-yaml Requires: python-httplib2 Requires: python-setuptools Requires: python-six Requires: sshpass %endif %description Ansible is a radically simple model-driven configuration management, multi-node deployment, and remote task execution system. Ansible works over SSH and does not require any software or daemons to be installed on remote nodes. Extension modules can be written in any language and are transferred to managed machines automatically. %package -n ansible-test Summary: Tool for testing ansible plugin and module code Requires: %{name} = %{version}-%{release} %if 0%{?rhel} >= 8 # Will use the python3 stdlib venv #Requires: python3-virtualenv #BuildRequires: python3-virtualenv %else %if 0%{?rhel} >= 7 Requires: python-virtualenv BuildRequires: python-virtualenv %endif # Requires for RHEL 7 %endif # Requires for RHEL 8 # SUSE/openSUSE %if 0%{?suse_version} Requires: python-virtualenv BuildRequires: python-virtualenv %endif %description -n ansible-test Ansible is a radically simple model-driven configuration management, multi-node deployment, and remote task execution system. Ansible works over SSH and does not require any software or daemons to be installed on remote nodes. Extension modules can be written in any language and are transferred to managed machines automatically. This package installs the ansible-test command for testing modules and plugins developed for ansible. %prep %setup -q -n %{name}-%{upstream_version} %build %if %{with_python2} %py2_build %endif %if %{with_python3} %py3_build %endif %install %if %{with_python2} %{__python2} setup.py install --root=%{buildroot} for i in %{buildroot}/%{_bindir}/{ansible,ansible-console,ansible-doc,ansible-galaxy,ansible-playbook,ansible-pull,ansible-vault} ; do mv $i $i-%{python2_version} ln -s %{_bindir}/$(basename $i)-%{python2_version} $i ln -s %{_bindir}/$(basename $i)-%{python2_version} $i-2 done %endif %if %{with_python3} %{__python3} setup.py install --root=%{buildroot} %endif # Amazon Linux doesn't install to dist-packages but python_sitelib expands to # that location and the python interpreter expects things to be there. if expr x'%{python_sitelib}' : 'x.*dist-packages/\?' ; then DEST_DIR='%{buildroot}%{python_sitelib}' SOURCE_DIR=$(echo "$DEST_DIR" | sed 's/dist-packages/site-packages/g') if test -d "$SOURCE_DIR" -a ! -d "$DEST_DIR" ; then mv $SOURCE_DIR $DEST_DIR fi fi # Create system directories that Ansible defines as default locations in # ansible/config/base.yml DATADIR_LOCATIONS='%{_datadir}/ansible/collections %{_datadir}/ansible/plugins/doc_fragments %{_datadir}/ansible/plugins/action %{_datadir}/ansible/plugins/become %{_datadir}/ansible/plugins/cache %{_datadir}/ansible/plugins/callback %{_datadir}/ansible/plugins/cliconf %{_datadir}/ansible/plugins/connection %{_datadir}/ansible/plugins/filter %{_datadir}/ansible/plugins/httpapi %{_datadir}/ansible/plugins/inventory %{_datadir}/ansible/plugins/lookup %{_datadir}/ansible/plugins/modules %{_datadir}/ansible/plugins/module_utils %{_datadir}/ansible/plugins/netconf %{_datadir}/ansible/roles %{_datadir}/ansible/plugins/strategy %{_datadir}/ansible/plugins/terminal %{_datadir}/ansible/plugins/test %{_datadir}/ansible/plugins/vars' UPSTREAM_DATADIR_LOCATIONS=$(grep -ri default lib/ansible/config/base.yml| tr ':' '\n' | grep '/usr/share/ansible') if [ "$SYSTEM_LOCATIONS" != "$UPSTREAM_SYSTEM_LOCATIONS" ] ; then echo "The upstream Ansible datadir locations have changed. Spec file needs to be updated" exit 1 fi mkdir -p %{buildroot}%{_datadir}/ansible/plugins/ for location in $DATADIR_LOCATIONS ; do mkdir %{buildroot}"$location" done mkdir -p %{buildroot}%{_sysconfdir}/ansible/ mkdir -p %{buildroot}%{_sysconfdir}/ansible/roles/ cp examples/hosts %{buildroot}%{_sysconfdir}/ansible/ cp examples/ansible.cfg %{buildroot}%{_sysconfdir}/ansible/ mkdir -p %{buildroot}/%{_mandir}/man1/ cp -v docs/man/man1/*.1 %{buildroot}/%{_mandir}/man1/ cp -pr docs/docsite/rst . %clean rm -rf %{buildroot} %check # We need pytest-4.5.0 or greater %if 0%{?fedora} >= 31 ln -s /usr/bin/pytest-3 bin/pytest %{__python3} bin/ansible-test units -v --python %{python3_version} %endif %files %defattr(-,root,root) %{_bindir}/ansible* %config(noreplace) %{_sysconfdir}/ansible/ %doc README.rst PKG-INFO COPYING changelogs/CHANGELOG*.rst %doc %{_mandir}/man1/ansible* %{_datadir}/ansible/ %if %{with_python3} %{python3_sitelib}/ansible* %exclude %{python3_sitelib}/ansible_test %endif %if %{with_python2} %{python2_sitelib}/ansible* %exclude %{python2_sitelib}/ansible_test %endif %files -n ansible-test %{_bindir}/ansible-test %if %{with_python3} %{python3_sitelib}/ansible_test %endif %if %{with_python2} %{python2_sitelib}/ansible_test %endif %changelog * %{release_date} Ansible, Inc. <[email protected]> - %{rpmversion}-%{rpmrelease} - Release %{rpmversion}-%{rpmrelease}
closed
ansible/ansible
https://github.com/ansible/ansible
64,128
Incorrect indirect variable expansion if accessed from intermediate result
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> If a hostvar definition contains another variable, it can be expanded properly normally, but if we first store parent in an intermediate variable and accessed from the there, the variable is no longer expanded. See my full reproducible case below for details. But in short, suppose we have two hostvars: ``` x: 100 y: "{{ x }}" ``` then the following prints out string ``{{ x }}`` instead of `100`: ``` - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['the_host_name'] }}" ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> core language vars ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = None configured module search path = ['/Users/likan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/Cellar/ansible/2.8.5_1/libexec/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] ``` ##### CONFIGURATION Empty result from `"ansible-config dump --only-changed"`. <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> This is target OS independent. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> The minimum case to reproduce only consists of three files: ```paste [hidden] tree . . ├── group_vars │   └── all ├── hosts └── site.yaml 1 directory, 3 files ``` The host file defines a single host named `h1`. And site.yaml looks like this: <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: all tasks: - debug: msg: "{{ hostvars['h1']['x'] }}" - debug: msg: "{{ hostvars['h1']['y'] }}" - debug: msg: "{{ hostvars_['x'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" ``` groups_vars/all content: ```yaml --- x: 100 y: "{{ x }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The last task should also print out 100. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> First three tasks print correct result, but last one are expaneded to string "{{ x }}". <!--- Paste verbatim command output between quotes --> ```paste below [hidden] ansible-playbook --ask-pass -u root -i hosts site.yaml SSH password: PLAY [all] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************************************************************************************** ok: [h1] TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "{{ x }}" } PLAY RECAP ***************************************************************************************************************************************************************************************************** h1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/64128
https://github.com/ansible/ansible/pull/64282
5dff5603af958151fe4c2d2d292ede9d853943de
371d7aae316f5fdc756c9c7173c20c15f40305b5
2019-10-30T23:42:33Z
python
2019-11-01T19:51:34Z
changelogs/fragments/64282-hostvarsvars-templating.yaml
closed
ansible/ansible
https://github.com/ansible/ansible
64,128
Incorrect indirect variable expansion if accessed from intermediate result
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> If a hostvar definition contains another variable, it can be expanded properly normally, but if we first store parent in an intermediate variable and accessed from the there, the variable is no longer expanded. See my full reproducible case below for details. But in short, suppose we have two hostvars: ``` x: 100 y: "{{ x }}" ``` then the following prints out string ``{{ x }}`` instead of `100`: ``` - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['the_host_name'] }}" ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> core language vars ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = None configured module search path = ['/Users/likan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/Cellar/ansible/2.8.5_1/libexec/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] ``` ##### CONFIGURATION Empty result from `"ansible-config dump --only-changed"`. <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> This is target OS independent. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> The minimum case to reproduce only consists of three files: ```paste [hidden] tree . . ├── group_vars │   └── all ├── hosts └── site.yaml 1 directory, 3 files ``` The host file defines a single host named `h1`. And site.yaml looks like this: <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: all tasks: - debug: msg: "{{ hostvars['h1']['x'] }}" - debug: msg: "{{ hostvars['h1']['y'] }}" - debug: msg: "{{ hostvars_['x'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" ``` groups_vars/all content: ```yaml --- x: 100 y: "{{ x }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The last task should also print out 100. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> First three tasks print correct result, but last one are expaneded to string "{{ x }}". <!--- Paste verbatim command output between quotes --> ```paste below [hidden] ansible-playbook --ask-pass -u root -i hosts site.yaml SSH password: PLAY [all] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************************************************************************************** ok: [h1] TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "{{ x }}" } PLAY RECAP ***************************************************************************************************************************************************************************************************** h1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/64128
https://github.com/ansible/ansible/pull/64282
5dff5603af958151fe4c2d2d292ede9d853943de
371d7aae316f5fdc756c9c7173c20c15f40305b5
2019-10-30T23:42:33Z
python
2019-11-01T19:51:34Z
lib/ansible/vars/hostvars.py
# (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from jinja2.runtime import Undefined from ansible.module_utils.common._collections_compat import Mapping from ansible.template import Templar STATIC_VARS = [ 'ansible_version', 'ansible_play_hosts', 'ansible_dependent_role_names', 'ansible_play_role_names', 'ansible_role_names', 'inventory_hostname', 'inventory_hostname_short', 'inventory_file', 'inventory_dir', 'groups', 'group_names', 'omit', 'playbook_dir', 'play_hosts', 'role_names', 'ungrouped', ] __all__ = ['HostVars', 'HostVarsVars'] # Note -- this is a Mapping, not a MutableMapping class HostVars(Mapping): ''' A special view of vars_cache that adds values from the inventory when needed. ''' def __init__(self, inventory, variable_manager, loader): self._lookup = dict() self._inventory = inventory self._loader = loader self._variable_manager = variable_manager variable_manager._hostvars = self def set_variable_manager(self, variable_manager): self._variable_manager = variable_manager variable_manager._hostvars = self def set_inventory(self, inventory): self._inventory = inventory def _find_host(self, host_name): # does not use inventory.hosts so it can create localhost on demand return self._inventory.get_host(host_name) def raw_get(self, host_name): ''' Similar to __getitem__, however the returned data is not run through the templating engine to expand variables in the hostvars. ''' host = self._find_host(host_name) if host is None: return Undefined(name="hostvars['%s']" % host_name) return self._variable_manager.get_vars(host=host, include_hostvars=False) def __getitem__(self, host_name): data = self.raw_get(host_name) if isinstance(data, Undefined): return data return HostVarsVars(data, loader=self._loader) def set_host_variable(self, host, varname, value): self._variable_manager.set_host_variable(host, varname, value) def set_nonpersistent_facts(self, host, facts): self._variable_manager.set_nonpersistent_facts(host, facts) def set_host_facts(self, host, facts): self._variable_manager.set_host_facts(host, facts) def __contains__(self, host_name): # does not use inventory.hosts so it can create localhost on demand return self._find_host(host_name) is not None def __iter__(self): for host in self._inventory.hosts: yield host def __len__(self): return len(self._inventory.hosts) def __repr__(self): out = {} for host in self._inventory.hosts: out[host] = self.get(host) return repr(out) class HostVarsVars(Mapping): def __init__(self, variables, loader): self._vars = variables self._loader = loader def __getitem__(self, var): templar = Templar(variables=self._vars, loader=self._loader) foo = templar.template(self._vars[var], fail_on_undefined=False, static_vars=STATIC_VARS) return foo def __contains__(self, var): return (var in self._vars) def __iter__(self): for var in self._vars.keys(): yield var def __len__(self): return len(self._vars.keys()) def __repr__(self): return repr(self._vars)
closed
ansible/ansible
https://github.com/ansible/ansible
64,128
Incorrect indirect variable expansion if accessed from intermediate result
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> If a hostvar definition contains another variable, it can be expanded properly normally, but if we first store parent in an intermediate variable and accessed from the there, the variable is no longer expanded. See my full reproducible case below for details. But in short, suppose we have two hostvars: ``` x: 100 y: "{{ x }}" ``` then the following prints out string ``{{ x }}`` instead of `100`: ``` - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['the_host_name'] }}" ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> core language vars ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = None configured module search path = ['/Users/likan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/Cellar/ansible/2.8.5_1/libexec/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] ``` ##### CONFIGURATION Empty result from `"ansible-config dump --only-changed"`. <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> This is target OS independent. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> The minimum case to reproduce only consists of three files: ```paste [hidden] tree . . ├── group_vars │   └── all ├── hosts └── site.yaml 1 directory, 3 files ``` The host file defines a single host named `h1`. And site.yaml looks like this: <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: all tasks: - debug: msg: "{{ hostvars['h1']['x'] }}" - debug: msg: "{{ hostvars['h1']['y'] }}" - debug: msg: "{{ hostvars_['x'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" ``` groups_vars/all content: ```yaml --- x: 100 y: "{{ x }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The last task should also print out 100. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> First three tasks print correct result, but last one are expaneded to string "{{ x }}". <!--- Paste verbatim command output between quotes --> ```paste below [hidden] ansible-playbook --ask-pass -u root -i hosts site.yaml SSH password: PLAY [all] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************************************************************************************** ok: [h1] TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "{{ x }}" } PLAY RECAP ***************************************************************************************************************************************************************************************************** h1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/64128
https://github.com/ansible/ansible/pull/64282
5dff5603af958151fe4c2d2d292ede9d853943de
371d7aae316f5fdc756c9c7173c20c15f40305b5
2019-10-30T23:42:33Z
python
2019-11-01T19:51:34Z
test/integration/targets/var_templating/group_vars/all.yml
closed
ansible/ansible
https://github.com/ansible/ansible
64,128
Incorrect indirect variable expansion if accessed from intermediate result
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> If a hostvar definition contains another variable, it can be expanded properly normally, but if we first store parent in an intermediate variable and accessed from the there, the variable is no longer expanded. See my full reproducible case below for details. But in short, suppose we have two hostvars: ``` x: 100 y: "{{ x }}" ``` then the following prints out string ``{{ x }}`` instead of `100`: ``` - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['the_host_name'] }}" ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> core language vars ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = None configured module search path = ['/Users/likan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/Cellar/ansible/2.8.5_1/libexec/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] ``` ##### CONFIGURATION Empty result from `"ansible-config dump --only-changed"`. <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> This is target OS independent. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> The minimum case to reproduce only consists of three files: ```paste [hidden] tree . . ├── group_vars │   └── all ├── hosts └── site.yaml 1 directory, 3 files ``` The host file defines a single host named `h1`. And site.yaml looks like this: <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: all tasks: - debug: msg: "{{ hostvars['h1']['x'] }}" - debug: msg: "{{ hostvars['h1']['y'] }}" - debug: msg: "{{ hostvars_['x'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" ``` groups_vars/all content: ```yaml --- x: 100 y: "{{ x }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The last task should also print out 100. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> First three tasks print correct result, but last one are expaneded to string "{{ x }}". <!--- Paste verbatim command output between quotes --> ```paste below [hidden] ansible-playbook --ask-pass -u root -i hosts site.yaml SSH password: PLAY [all] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************************************************************************************** ok: [h1] TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "{{ x }}" } PLAY RECAP ***************************************************************************************************************************************************************************************************** h1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/64128
https://github.com/ansible/ansible/pull/64282
5dff5603af958151fe4c2d2d292ede9d853943de
371d7aae316f5fdc756c9c7173c20c15f40305b5
2019-10-30T23:42:33Z
python
2019-11-01T19:51:34Z
test/integration/targets/var_templating/runme.sh
#!/usr/bin/env bash set -eux # this should succeed since we override the undefined variable ansible-playbook undefined.yml -i inventory -v "$@" -e '{"mytest": False}' # this should still work, just show that var is undefined in debug ansible-playbook undefined.yml -i inventory -v "$@" # this should work since we dont use the variable ansible-playbook undall.yml -i inventory -v "$@"
closed
ansible/ansible
https://github.com/ansible/ansible
64,128
Incorrect indirect variable expansion if accessed from intermediate result
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> If a hostvar definition contains another variable, it can be expanded properly normally, but if we first store parent in an intermediate variable and accessed from the there, the variable is no longer expanded. See my full reproducible case below for details. But in short, suppose we have two hostvars: ``` x: 100 y: "{{ x }}" ``` then the following prints out string ``{{ x }}`` instead of `100`: ``` - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['the_host_name'] }}" ``` ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> core language vars ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = None configured module search path = ['/Users/likan/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/Cellar/ansible/2.8.5_1/libexec/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] ``` ##### CONFIGURATION Empty result from `"ansible-config dump --only-changed"`. <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> This is target OS independent. ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> The minimum case to reproduce only consists of three files: ```paste [hidden] tree . . ├── group_vars │   └── all ├── hosts └── site.yaml 1 directory, 3 files ``` The host file defines a single host named `h1`. And site.yaml looks like this: <!--- Paste example playbooks or commands between quotes below --> ```yaml --- - hosts: all tasks: - debug: msg: "{{ hostvars['h1']['x'] }}" - debug: msg: "{{ hostvars['h1']['y'] }}" - debug: msg: "{{ hostvars_['x'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" - debug: msg: "{{ hostvars_['y'] }}" vars: hostvars_: "{{ hostvars['h1'] }}" ``` groups_vars/all content: ```yaml --- x: 100 y: "{{ x }}" ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> The last task should also print out 100. ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> First three tasks print correct result, but last one are expaneded to string "{{ x }}". <!--- Paste verbatim command output between quotes --> ```paste below [hidden] ansible-playbook --ask-pass -u root -i hosts site.yaml SSH password: PLAY [all] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************************************************************************************** ok: [h1] TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "100" } TASK [debug] *************************************************************************************************************************************************************************************************** ok: [h1] => { "msg": "{{ x }}" } PLAY RECAP ***************************************************************************************************************************************************************************************************** h1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 ```
https://github.com/ansible/ansible/issues/64128
https://github.com/ansible/ansible/pull/64282
5dff5603af958151fe4c2d2d292ede9d853943de
371d7aae316f5fdc756c9c7173c20c15f40305b5
2019-10-30T23:42:33Z
python
2019-11-01T19:51:34Z
test/integration/targets/var_templating/task_vars_templating.yml
closed
ansible/ansible
https://github.com/ansible/ansible
63,937
vmware inventory plugin env variables
##### SUMMARY Environment variables in plugin do not match Tower credential injector ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lib/ansible/plugins/inventory/vmware_vm_inventory.py ##### ANSIBLE VERSION ``` ansible 2.8.0 config file = /etc/ansible/ansible.cfg configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /bin/ansible python version = 2.7.5 (default, May 20 2019, 12:21:26) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] ``` ##### CONFIGURATION ```paste below ``` ##### OS / ENVIRONMENT Red Hat Enterprise Linux Server release 7.5 ##### STEPS TO REPRODUCE use vmware inventory plugin with vCenter credential in Ansible Tower ```yaml --- plugin: vmware_vm_inventory validate_certs: False ``` ##### EXPECTED RESULTS inventory should be parsed ##### ACTUAL RESULTS ```paste below [WARNING]: * Failed to parse /var/lib/awx/projects/_16__ansible_inventory/tests/vmware_vm_inventory.yaml with auto plugin: No setting was provided for required configuration plugin_type: inventory plugin: vmware_vm_inventory setting: username ```
https://github.com/ansible/ansible/issues/63937
https://github.com/ansible/ansible/pull/63938
6e07d4c1d932823331eba895d835b54105e394d6
bbbaf0dfe775bb7ab8584244a7162cd3a9a5f9a5
2019-10-25T02:43:08Z
python
2019-11-01T20:16:56Z
lib/ansible/plugins/inventory/vmware_vm_inventory.py
# # Copyright: (c) 2018, Ansible Project # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' name: vmware_vm_inventory plugin_type: inventory short_description: VMware Guest inventory source version_added: "2.7" author: - Abhijeet Kasurde (@Akasurde) description: - Get virtual machines as inventory hosts from VMware environment. - Uses any file which ends with vmware.yml or vmware.yaml as a YAML configuration file. - The inventory_hostname is always the 'Name' and UUID of the virtual machine. UUID is added as VMware allows virtual machines with the same name. extends_documentation_fragment: - inventory_cache requirements: - "Python >= 2.7" - "PyVmomi" - "requests >= 2.3" - "vSphere Automation SDK - For tag feature" - "vCloud Suite SDK - For tag feature" options: hostname: description: Name of vCenter or ESXi server. required: True env: - name: VMWARE_SERVER username: description: Name of vSphere admin user. required: True env: - name: VMWARE_USERNAME password: description: Password of vSphere admin user. required: True env: - name: VMWARE_PASSWORD port: description: Port number used to connect to vCenter or ESXi Server. default: 443 env: - name: VMWARE_PORT validate_certs: description: - Allows connection when SSL certificates are not valid. Set to C(false) when certificates are not trusted. default: True type: boolean with_tags: description: - Include tags and associated virtual machines. - Requires 'vSphere Automation SDK' library to be installed on the given controller machine. - Please refer following URLs for installation steps - 'https://code.vmware.com/web/sdk/65/vsphere-automation-python' default: False type: boolean properties: description: - Specify the list of VMware schema properties associated with the VM. - These properties will be populated in hostvars of the given VM. - Each value in the list specifies the path to a specific property in VM object. type: list default: [ 'name', 'config.cpuHotAddEnabled', 'config.cpuHotRemoveEnabled', 'config.instanceUuid', 'config.hardware.numCPU', 'config.template', 'config.name', 'guest.hostName', 'guest.ipAddress', 'guest.guestId', 'guest.guestState', 'runtime.maxMemoryUsage', 'customValue' ] version_added: "2.9" ''' EXAMPLES = ''' # Sample configuration file for VMware Guest dynamic inventory plugin: vmware_vm_inventory strict: False hostname: 10.65.223.31 username: [email protected] password: Esxi@123$% validate_certs: False with_tags: True # Gather minimum set of properties for VMware guest plugin: vmware_vm_inventory strict: False hostname: 10.65.223.31 username: [email protected] password: Esxi@123$% validate_certs: False with_tags: False properties: - 'name' - 'guest.ipAddress' ''' import ssl import atexit from ansible.errors import AnsibleError, AnsibleParserError try: # requests is required for exception handling of the ConnectionError import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from pyVim import connect from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False try: from com.vmware.vapi.std_client import DynamicID from vmware.vapi.vsphere.client import create_vsphere_client HAS_VSPHERE = True except ImportError: HAS_VSPHERE = False from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable class BaseVMwareInventory: def __init__(self, hostname, username, password, port, validate_certs, with_tags): self.hostname = hostname self.username = username self.password = password self.port = port self.with_tags = with_tags self.validate_certs = validate_certs self.content = None self.rest_content = None def do_login(self): """ Check requirements and do login """ self.check_requirements() self.content = self._login() if self.with_tags: self.rest_content = self._login_vapi() def _login_vapi(self): """ Login to vCenter API using REST call Returns: connection object """ session = requests.Session() session.verify = self.validate_certs if not self.validate_certs: # Disable warning shown at stdout requests.packages.urllib3.disable_warnings() client = create_vsphere_client(server=self.hostname, username=self.username, password=self.password, session=session) if client is None: raise AnsibleError("Failed to login to %s using %s" % (self.hostname, self.username)) return client def _login(self): """ Login to vCenter or ESXi server Returns: connection object """ if self.validate_certs and not hasattr(ssl, 'SSLContext'): raise AnsibleError('pyVim does not support changing verification mode with python < 2.7.9. Either update ' 'python or set validate_certs to false in configuration YAML file.') ssl_context = None if not self.validate_certs and hasattr(ssl, 'SSLContext'): ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ssl_context.verify_mode = ssl.CERT_NONE service_instance = None try: service_instance = connect.SmartConnect(host=self.hostname, user=self.username, pwd=self.password, sslContext=ssl_context, port=self.port) except vim.fault.InvalidLogin as e: raise AnsibleParserError("Unable to log on to vCenter or ESXi API at %s:%s as %s: %s" % (self.hostname, self.port, self.username, e.msg)) except vim.fault.NoPermission as e: raise AnsibleParserError("User %s does not have required permission" " to log on to vCenter or ESXi API at %s:%s : %s" % (self.username, self.hostname, self.port, e.msg)) except (requests.ConnectionError, ssl.SSLError) as e: raise AnsibleParserError("Unable to connect to vCenter or ESXi API at %s on TCP/%s: %s" % (self.hostname, self.port, e)) except vmodl.fault.InvalidRequest as e: # Request is malformed raise AnsibleParserError("Failed to get a response from server %s:%s as " "request is malformed: %s" % (self.hostname, self.port, e.msg)) except Exception as e: raise AnsibleParserError("Unknown error while connecting to vCenter or ESXi API at %s:%s : %s" % (self.hostname, self.port, e)) if service_instance is None: raise AnsibleParserError("Unknown error while connecting to vCenter or ESXi API at %s:%s" % (self.hostname, self.port)) atexit.register(connect.Disconnect, service_instance) return service_instance.RetrieveContent() def check_requirements(self): """ Check all requirements for this inventory are satisified""" if not HAS_REQUESTS: raise AnsibleParserError('Please install "requests" Python module as this is required' ' for VMware Guest dynamic inventory plugin.') elif not HAS_PYVMOMI: raise AnsibleParserError('Please install "PyVmomi" Python module as this is required' ' for VMware Guest dynamic inventory plugin.') if HAS_REQUESTS: # Pyvmomi 5.5 and onwards requires requests 2.3 # https://github.com/vmware/pyvmomi/blob/master/requirements.txt required_version = (2, 3) requests_version = requests.__version__.split(".")[:2] try: requests_major_minor = tuple(map(int, requests_version)) except ValueError: raise AnsibleParserError("Failed to parse 'requests' library version.") if requests_major_minor < required_version: raise AnsibleParserError("'requests' library version should" " be >= %s, found: %s." % (".".join([str(w) for w in required_version]), requests.__version__)) if not HAS_VSPHERE and self.with_tags: raise AnsibleError("Unable to find 'vSphere Automation SDK' Python library which is required." " Please refer this URL for installation steps" " - https://code.vmware.com/web/sdk/65/vsphere-automation-python") if not all([self.hostname, self.username, self.password]): raise AnsibleError("Missing one of the following : hostname, username, password. Please read " "the documentation for more information.") def _get_managed_objects_properties(self, vim_type, properties=None): """ Look up a Managed Object Reference in vCenter / ESXi Environment :param vim_type: Type of vim object e.g, for datacenter - vim.Datacenter :param properties: List of properties related to vim object e.g. Name :return: local content object """ # Get Root Folder root_folder = self.content.rootFolder if properties is None: properties = ['name'] # Create Container View with default root folder mor = self.content.viewManager.CreateContainerView(root_folder, [vim_type], True) # Create Traversal spec traversal_spec = vmodl.query.PropertyCollector.TraversalSpec( name="traversal_spec", path='view', skip=False, type=vim.view.ContainerView ) # Create Property Spec property_spec = vmodl.query.PropertyCollector.PropertySpec( type=vim_type, # Type of object to retrieved all=False, pathSet=properties ) # Create Object Spec object_spec = vmodl.query.PropertyCollector.ObjectSpec( obj=mor, skip=True, selectSet=[traversal_spec] ) # Create Filter Spec filter_spec = vmodl.query.PropertyCollector.FilterSpec( objectSet=[object_spec], propSet=[property_spec], reportMissingObjectsInResults=False ) return self.content.propertyCollector.RetrieveContents([filter_spec]) @staticmethod def _get_object_prop(vm, attributes): """Safely get a property or return None""" result = vm for attribute in attributes: try: result = getattr(result, attribute) except (AttributeError, IndexError): return None return result class InventoryModule(BaseInventoryPlugin, Cacheable): NAME = 'vmware_vm_inventory' def verify_file(self, path): """ Verify plugin configuration file and mark this plugin active Args: path: Path of configuration YAML file Returns: True if everything is correct, else False """ valid = False if super(InventoryModule, self).verify_file(path): if path.endswith(('vmware.yaml', 'vmware.yml')): valid = True return valid def parse(self, inventory, loader, path, cache=True): """ Parses the inventory file """ super(InventoryModule, self).parse(inventory, loader, path, cache=cache) cache_key = self.get_cache_key(path) config_data = self._read_config_data(path) # set _options from config data self._consume_options(config_data) self.pyv = BaseVMwareInventory( hostname=self.get_option('hostname'), username=self.get_option('username'), password=self.get_option('password'), port=self.get_option('port'), with_tags=self.get_option('with_tags'), validate_certs=self.get_option('validate_certs') ) self.pyv.do_login() self.pyv.check_requirements() source_data = None if cache: cache = self.get_option('cache') update_cache = False if cache: try: source_data = self._cache[cache_key] except KeyError: update_cache = True using_current_cache = cache and not update_cache cacheable_results = self._populate_from_source(source_data, using_current_cache) if update_cache: self._cache[cache_key] = cacheable_results def _populate_from_cache(self, source_data): """ Populate cache using source data """ hostvars = source_data.pop('_meta', {}).get('hostvars', {}) for group in source_data: if group == 'all': continue else: self.inventory.add_group(group) hosts = source_data[group].get('hosts', []) for host in hosts: self._populate_host_vars([host], hostvars.get(host, {}), group) self.inventory.add_child('all', group) def _populate_from_source(self, source_data, using_current_cache): """ Populate inventory data from direct source """ if using_current_cache: self._populate_from_cache(source_data) return source_data cacheable_results = {'_meta': {'hostvars': {}}} hostvars = {} objects = self.pyv._get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name']) if self.pyv.with_tags: tag_svc = self.pyv.rest_content.tagging.Tag tag_association = self.pyv.rest_content.tagging.TagAssociation tags_info = dict() tags = tag_svc.list() for tag in tags: tag_obj = tag_svc.get(tag) tags_info[tag_obj.id] = tag_obj.name if tag_obj.name not in cacheable_results: cacheable_results[tag_obj.name] = {'hosts': []} self.inventory.add_group(tag_obj.name) for vm_obj in objects: for vm_obj_property in vm_obj.propSet: # VMware does not provide a way to uniquely identify VM by its name # i.e. there can be two virtual machines with same name # Appending "_" and VMware UUID to make it unique if not vm_obj.obj.config: # Sometime orphaned VMs return no configurations continue current_host = vm_obj_property.val + "_" + vm_obj.obj.config.uuid if current_host not in hostvars: hostvars[current_host] = {} self.inventory.add_host(current_host) host_ip = vm_obj.obj.guest.ipAddress if host_ip: self.inventory.set_variable(current_host, 'ansible_host', host_ip) self._populate_host_properties(vm_obj, current_host) # Only gather facts related to tag if vCloud and vSphere is installed. if HAS_VSPHERE and self.pyv.with_tags: # Add virtual machine to appropriate tag group vm_mo_id = vm_obj.obj._GetMoId() vm_dynamic_id = DynamicID(type='VirtualMachine', id=vm_mo_id) attached_tags = tag_association.list_attached_tags(vm_dynamic_id) for tag_id in attached_tags: self.inventory.add_child(tags_info[tag_id], current_host) cacheable_results[tags_info[tag_id]]['hosts'].append(current_host) # Based on power state of virtual machine vm_power = str(vm_obj.obj.summary.runtime.powerState) if vm_power not in cacheable_results: cacheable_results[vm_power] = {'hosts': []} self.inventory.add_group(vm_power) cacheable_results[vm_power]['hosts'].append(current_host) self.inventory.add_child(vm_power, current_host) # Based on guest id vm_guest_id = vm_obj.obj.config.guestId if vm_guest_id and vm_guest_id not in cacheable_results: cacheable_results[vm_guest_id] = {'hosts': []} self.inventory.add_group(vm_guest_id) cacheable_results[vm_guest_id]['hosts'].append(current_host) self.inventory.add_child(vm_guest_id, current_host) for host in hostvars: h = self.inventory.get_host(host) cacheable_results['_meta']['hostvars'][h.name] = h.vars return cacheable_results def _populate_host_properties(self, vm_obj, current_host): # Load VM properties in host_vars vm_properties = self.get_option('properties') or [] field_mgr = self.pyv.content.customFieldsManager.field for vm_prop in vm_properties: if vm_prop == 'customValue': for cust_value in vm_obj.obj.customValue: self.inventory.set_variable(current_host, [y.name for y in field_mgr if y.key == cust_value.key][0], cust_value.value) else: vm_value = self.pyv._get_object_prop(vm_obj.obj, vm_prop.split(".")) self.inventory.set_variable(current_host, vm_prop, vm_value)
closed
ansible/ansible
https://github.com/ansible/ansible
63,936
VMware inventory not loaded by auto plugin
##### SUMMARY The vmware_vm_inventory plugin cannot verify the inventory file when being loaded via the auto plugin ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME lib/ansible/plugins/inventory/vmware_vm_inventory.py ##### ANSIBLE VERSION ```paste below ansible 2.8.1 config file = None configured module search path = ['/Users/wtome/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/Cellar/ansible/2.8.1_1/libexec/lib/python3.7/site-packages/ansible executable location = /usr/local/bin/ansible python version = 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] ``` ##### CONFIGURATION ```paste below ``` ##### OS / ENVIRONMENT MacOS 10.14.6 ##### STEPS TO REPRODUCE vmware_vm_inventory.yaml ```yaml --- plugin: vmware_vm_inventory strict: True ``` ##### EXPECTED RESULTS Inventory should be parsed from vCenter ##### ACTUAL RESULTS ```paste below ansible-inventory -i vmware_vm_inventory.yaml --playbook-dir=. --list [WARNING]: * Failed to parse /Users/wtome/ansible- inventory/tests/vmware_vm_inventory.yaml with auto plugin: inventory config '/Users/wtome/ansible- inventory/tests/vmware_vm_inventory.yaml' could not be verified by plugin 'vmware_vm_inventory' ```
https://github.com/ansible/ansible/issues/63936
https://github.com/ansible/ansible/pull/63938
6e07d4c1d932823331eba895d835b54105e394d6
bbbaf0dfe775bb7ab8584244a7162cd3a9a5f9a5
2019-10-25T02:16:06Z
python
2019-11-01T20:16:56Z
lib/ansible/plugins/inventory/vmware_vm_inventory.py
# # Copyright: (c) 2018, Ansible Project # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' name: vmware_vm_inventory plugin_type: inventory short_description: VMware Guest inventory source version_added: "2.7" author: - Abhijeet Kasurde (@Akasurde) description: - Get virtual machines as inventory hosts from VMware environment. - Uses any file which ends with vmware.yml or vmware.yaml as a YAML configuration file. - The inventory_hostname is always the 'Name' and UUID of the virtual machine. UUID is added as VMware allows virtual machines with the same name. extends_documentation_fragment: - inventory_cache requirements: - "Python >= 2.7" - "PyVmomi" - "requests >= 2.3" - "vSphere Automation SDK - For tag feature" - "vCloud Suite SDK - For tag feature" options: hostname: description: Name of vCenter or ESXi server. required: True env: - name: VMWARE_SERVER username: description: Name of vSphere admin user. required: True env: - name: VMWARE_USERNAME password: description: Password of vSphere admin user. required: True env: - name: VMWARE_PASSWORD port: description: Port number used to connect to vCenter or ESXi Server. default: 443 env: - name: VMWARE_PORT validate_certs: description: - Allows connection when SSL certificates are not valid. Set to C(false) when certificates are not trusted. default: True type: boolean with_tags: description: - Include tags and associated virtual machines. - Requires 'vSphere Automation SDK' library to be installed on the given controller machine. - Please refer following URLs for installation steps - 'https://code.vmware.com/web/sdk/65/vsphere-automation-python' default: False type: boolean properties: description: - Specify the list of VMware schema properties associated with the VM. - These properties will be populated in hostvars of the given VM. - Each value in the list specifies the path to a specific property in VM object. type: list default: [ 'name', 'config.cpuHotAddEnabled', 'config.cpuHotRemoveEnabled', 'config.instanceUuid', 'config.hardware.numCPU', 'config.template', 'config.name', 'guest.hostName', 'guest.ipAddress', 'guest.guestId', 'guest.guestState', 'runtime.maxMemoryUsage', 'customValue' ] version_added: "2.9" ''' EXAMPLES = ''' # Sample configuration file for VMware Guest dynamic inventory plugin: vmware_vm_inventory strict: False hostname: 10.65.223.31 username: [email protected] password: Esxi@123$% validate_certs: False with_tags: True # Gather minimum set of properties for VMware guest plugin: vmware_vm_inventory strict: False hostname: 10.65.223.31 username: [email protected] password: Esxi@123$% validate_certs: False with_tags: False properties: - 'name' - 'guest.ipAddress' ''' import ssl import atexit from ansible.errors import AnsibleError, AnsibleParserError try: # requests is required for exception handling of the ConnectionError import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False try: from pyVim import connect from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False try: from com.vmware.vapi.std_client import DynamicID from vmware.vapi.vsphere.client import create_vsphere_client HAS_VSPHERE = True except ImportError: HAS_VSPHERE = False from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable class BaseVMwareInventory: def __init__(self, hostname, username, password, port, validate_certs, with_tags): self.hostname = hostname self.username = username self.password = password self.port = port self.with_tags = with_tags self.validate_certs = validate_certs self.content = None self.rest_content = None def do_login(self): """ Check requirements and do login """ self.check_requirements() self.content = self._login() if self.with_tags: self.rest_content = self._login_vapi() def _login_vapi(self): """ Login to vCenter API using REST call Returns: connection object """ session = requests.Session() session.verify = self.validate_certs if not self.validate_certs: # Disable warning shown at stdout requests.packages.urllib3.disable_warnings() client = create_vsphere_client(server=self.hostname, username=self.username, password=self.password, session=session) if client is None: raise AnsibleError("Failed to login to %s using %s" % (self.hostname, self.username)) return client def _login(self): """ Login to vCenter or ESXi server Returns: connection object """ if self.validate_certs and not hasattr(ssl, 'SSLContext'): raise AnsibleError('pyVim does not support changing verification mode with python < 2.7.9. Either update ' 'python or set validate_certs to false in configuration YAML file.') ssl_context = None if not self.validate_certs and hasattr(ssl, 'SSLContext'): ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ssl_context.verify_mode = ssl.CERT_NONE service_instance = None try: service_instance = connect.SmartConnect(host=self.hostname, user=self.username, pwd=self.password, sslContext=ssl_context, port=self.port) except vim.fault.InvalidLogin as e: raise AnsibleParserError("Unable to log on to vCenter or ESXi API at %s:%s as %s: %s" % (self.hostname, self.port, self.username, e.msg)) except vim.fault.NoPermission as e: raise AnsibleParserError("User %s does not have required permission" " to log on to vCenter or ESXi API at %s:%s : %s" % (self.username, self.hostname, self.port, e.msg)) except (requests.ConnectionError, ssl.SSLError) as e: raise AnsibleParserError("Unable to connect to vCenter or ESXi API at %s on TCP/%s: %s" % (self.hostname, self.port, e)) except vmodl.fault.InvalidRequest as e: # Request is malformed raise AnsibleParserError("Failed to get a response from server %s:%s as " "request is malformed: %s" % (self.hostname, self.port, e.msg)) except Exception as e: raise AnsibleParserError("Unknown error while connecting to vCenter or ESXi API at %s:%s : %s" % (self.hostname, self.port, e)) if service_instance is None: raise AnsibleParserError("Unknown error while connecting to vCenter or ESXi API at %s:%s" % (self.hostname, self.port)) atexit.register(connect.Disconnect, service_instance) return service_instance.RetrieveContent() def check_requirements(self): """ Check all requirements for this inventory are satisified""" if not HAS_REQUESTS: raise AnsibleParserError('Please install "requests" Python module as this is required' ' for VMware Guest dynamic inventory plugin.') elif not HAS_PYVMOMI: raise AnsibleParserError('Please install "PyVmomi" Python module as this is required' ' for VMware Guest dynamic inventory plugin.') if HAS_REQUESTS: # Pyvmomi 5.5 and onwards requires requests 2.3 # https://github.com/vmware/pyvmomi/blob/master/requirements.txt required_version = (2, 3) requests_version = requests.__version__.split(".")[:2] try: requests_major_minor = tuple(map(int, requests_version)) except ValueError: raise AnsibleParserError("Failed to parse 'requests' library version.") if requests_major_minor < required_version: raise AnsibleParserError("'requests' library version should" " be >= %s, found: %s." % (".".join([str(w) for w in required_version]), requests.__version__)) if not HAS_VSPHERE and self.with_tags: raise AnsibleError("Unable to find 'vSphere Automation SDK' Python library which is required." " Please refer this URL for installation steps" " - https://code.vmware.com/web/sdk/65/vsphere-automation-python") if not all([self.hostname, self.username, self.password]): raise AnsibleError("Missing one of the following : hostname, username, password. Please read " "the documentation for more information.") def _get_managed_objects_properties(self, vim_type, properties=None): """ Look up a Managed Object Reference in vCenter / ESXi Environment :param vim_type: Type of vim object e.g, for datacenter - vim.Datacenter :param properties: List of properties related to vim object e.g. Name :return: local content object """ # Get Root Folder root_folder = self.content.rootFolder if properties is None: properties = ['name'] # Create Container View with default root folder mor = self.content.viewManager.CreateContainerView(root_folder, [vim_type], True) # Create Traversal spec traversal_spec = vmodl.query.PropertyCollector.TraversalSpec( name="traversal_spec", path='view', skip=False, type=vim.view.ContainerView ) # Create Property Spec property_spec = vmodl.query.PropertyCollector.PropertySpec( type=vim_type, # Type of object to retrieved all=False, pathSet=properties ) # Create Object Spec object_spec = vmodl.query.PropertyCollector.ObjectSpec( obj=mor, skip=True, selectSet=[traversal_spec] ) # Create Filter Spec filter_spec = vmodl.query.PropertyCollector.FilterSpec( objectSet=[object_spec], propSet=[property_spec], reportMissingObjectsInResults=False ) return self.content.propertyCollector.RetrieveContents([filter_spec]) @staticmethod def _get_object_prop(vm, attributes): """Safely get a property or return None""" result = vm for attribute in attributes: try: result = getattr(result, attribute) except (AttributeError, IndexError): return None return result class InventoryModule(BaseInventoryPlugin, Cacheable): NAME = 'vmware_vm_inventory' def verify_file(self, path): """ Verify plugin configuration file and mark this plugin active Args: path: Path of configuration YAML file Returns: True if everything is correct, else False """ valid = False if super(InventoryModule, self).verify_file(path): if path.endswith(('vmware.yaml', 'vmware.yml')): valid = True return valid def parse(self, inventory, loader, path, cache=True): """ Parses the inventory file """ super(InventoryModule, self).parse(inventory, loader, path, cache=cache) cache_key = self.get_cache_key(path) config_data = self._read_config_data(path) # set _options from config data self._consume_options(config_data) self.pyv = BaseVMwareInventory( hostname=self.get_option('hostname'), username=self.get_option('username'), password=self.get_option('password'), port=self.get_option('port'), with_tags=self.get_option('with_tags'), validate_certs=self.get_option('validate_certs') ) self.pyv.do_login() self.pyv.check_requirements() source_data = None if cache: cache = self.get_option('cache') update_cache = False if cache: try: source_data = self._cache[cache_key] except KeyError: update_cache = True using_current_cache = cache and not update_cache cacheable_results = self._populate_from_source(source_data, using_current_cache) if update_cache: self._cache[cache_key] = cacheable_results def _populate_from_cache(self, source_data): """ Populate cache using source data """ hostvars = source_data.pop('_meta', {}).get('hostvars', {}) for group in source_data: if group == 'all': continue else: self.inventory.add_group(group) hosts = source_data[group].get('hosts', []) for host in hosts: self._populate_host_vars([host], hostvars.get(host, {}), group) self.inventory.add_child('all', group) def _populate_from_source(self, source_data, using_current_cache): """ Populate inventory data from direct source """ if using_current_cache: self._populate_from_cache(source_data) return source_data cacheable_results = {'_meta': {'hostvars': {}}} hostvars = {} objects = self.pyv._get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name']) if self.pyv.with_tags: tag_svc = self.pyv.rest_content.tagging.Tag tag_association = self.pyv.rest_content.tagging.TagAssociation tags_info = dict() tags = tag_svc.list() for tag in tags: tag_obj = tag_svc.get(tag) tags_info[tag_obj.id] = tag_obj.name if tag_obj.name not in cacheable_results: cacheable_results[tag_obj.name] = {'hosts': []} self.inventory.add_group(tag_obj.name) for vm_obj in objects: for vm_obj_property in vm_obj.propSet: # VMware does not provide a way to uniquely identify VM by its name # i.e. there can be two virtual machines with same name # Appending "_" and VMware UUID to make it unique if not vm_obj.obj.config: # Sometime orphaned VMs return no configurations continue current_host = vm_obj_property.val + "_" + vm_obj.obj.config.uuid if current_host not in hostvars: hostvars[current_host] = {} self.inventory.add_host(current_host) host_ip = vm_obj.obj.guest.ipAddress if host_ip: self.inventory.set_variable(current_host, 'ansible_host', host_ip) self._populate_host_properties(vm_obj, current_host) # Only gather facts related to tag if vCloud and vSphere is installed. if HAS_VSPHERE and self.pyv.with_tags: # Add virtual machine to appropriate tag group vm_mo_id = vm_obj.obj._GetMoId() vm_dynamic_id = DynamicID(type='VirtualMachine', id=vm_mo_id) attached_tags = tag_association.list_attached_tags(vm_dynamic_id) for tag_id in attached_tags: self.inventory.add_child(tags_info[tag_id], current_host) cacheable_results[tags_info[tag_id]]['hosts'].append(current_host) # Based on power state of virtual machine vm_power = str(vm_obj.obj.summary.runtime.powerState) if vm_power not in cacheable_results: cacheable_results[vm_power] = {'hosts': []} self.inventory.add_group(vm_power) cacheable_results[vm_power]['hosts'].append(current_host) self.inventory.add_child(vm_power, current_host) # Based on guest id vm_guest_id = vm_obj.obj.config.guestId if vm_guest_id and vm_guest_id not in cacheable_results: cacheable_results[vm_guest_id] = {'hosts': []} self.inventory.add_group(vm_guest_id) cacheable_results[vm_guest_id]['hosts'].append(current_host) self.inventory.add_child(vm_guest_id, current_host) for host in hostvars: h = self.inventory.get_host(host) cacheable_results['_meta']['hostvars'][h.name] = h.vars return cacheable_results def _populate_host_properties(self, vm_obj, current_host): # Load VM properties in host_vars vm_properties = self.get_option('properties') or [] field_mgr = self.pyv.content.customFieldsManager.field for vm_prop in vm_properties: if vm_prop == 'customValue': for cust_value in vm_obj.obj.customValue: self.inventory.set_variable(current_host, [y.name for y in field_mgr if y.key == cust_value.key][0], cust_value.value) else: vm_value = self.pyv._get_object_prop(vm_obj.obj, vm_prop.split(".")) self.inventory.set_variable(current_host, vm_prop, vm_value)
closed
ansible/ansible
https://github.com/ansible/ansible
62,958
os_server_action fails when 'wait' = ' no'
<!--- Verify first that your issue is not already reported on GitHub --> <!--- Also test if the latest release and devel branch are affected too --> <!--- Complete *all* sections as described, this form is processed automatically --> ##### SUMMARY <!--- Explain the problem briefly below --> When using ansible to stop an OpenStack VM, specifying wait=no occur a error. ##### ISSUE TYPE - Bug Report ##### COMPONENT NAME <!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure --> os_server_action ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes --> ```paste below ansible 2.8.5 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/ubuntu/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible python version = 2.7.12 (default, Aug 22 2019, 16:36:40) [GCC 5.4.0 20160609] ``` ##### CONFIGURATION <!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes --> ```paste below no change ``` ##### OS / ENVIRONMENT <!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. --> ubuntu 16.04 ##### STEPS TO REPRODUCE <!--- Describe exactly how to reproduce the problem, using a minimal test-case --> 1. create a openstack vm 2. stop a openstack vm by ansible. <!--- Paste example playbooks or commands between quotes below --> playbook ```yaml - name: Stop an OpenStack instance hosts: all gather_facts: no roles: - instance_action vars: instance_action: stop ``` ```yaml - name: Operate an OpenStack instance action os_server_action: action: "{{ instance_action }}" server: "{{ instance_id }}" wait: "{{ wait | default('yes') }}" verify: "{{ verify | default('yes') }}" ``` vars ```yaml instance_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx verify: no wait: no ``` <!--- HINT: You can paste gist.github.com links for larger files --> ##### EXPECTED RESULTS <!--- Describe what you expected to happen when running the steps above --> stop a OpenStack vm ##### ACTUAL RESULTS <!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) --> fail to stop a OpenStack vm <!--- Paste verbatim command output between quotes --> ```paste below ansible-playbook 2.8.5 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/ubuntu/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/dist-packages/ansible executable location = /usr/bin/ansible-playbook python version = 2.7.12 (default, Aug 22 2019, 16:36:40) [GCC 5.4.0 20160609] Using /etc/ansible/ansible.cfg as config file host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method script declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method auto declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method Parsed /etc/ansible/hosts inventory source with ini plugin PLAYBOOK: stop_instance.yml ***************************************************************************************************************************************************************** 1 plays in stop_instance.yml PLAY [Stop an OpenStack instance] *********************************************************************************************************************************************************** META: ran handlers TASK [instance_action : Operate an OpenStack instance action] ******************************************************************************************************************************* task path: /home/ubuntu/work/os-integ/roles/instance_action/tasks/main.yml:1 <127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: ubuntu <127.0.0.1> EXEC /bin/sh -c 'echo ~ubuntu && sleep 0' <127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/ubuntu/.ansible/tmp/ansible-tmp-1569828606.07-4717533724530 `" && echo ansible-tmp-1569828606.07-4717533724530="` echo /home/ubuntu/.ansible/tmp/ansible-tmp-1569828606.07-4717533724530 `" ) && sleep 0' <127.0.0.1> Attempting python interpreter discovery <127.0.0.1> EXEC /bin/sh -c 'echo PLATFORM; uname; echo FOUND; command -v '"'"'/usr/bin/python'"'"'; command -v '"'"'python3.7'"'"'; command -v '"'"'python3.6'"'"'; command -v '"'"'python3.5'"'"'; command -v '"'"'python2.7'"'"'; command -v '"'"'python2.6'"'"'; command -v '"'"'/usr/libexec/platform-python'"'"'; command -v '"'"'/usr/bin/python3'"'"'; command -v '"'"'python'"'"'; echo ENDFOUND && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python && sleep 0' Using module file /usr/lib/python2.7/dist-packages/ansible/modules/cloud/openstack/os_server_action.py <127.0.0.1> PUT /home/ubuntu/.ansible/tmp/ansible-local-71929SqXFy/tmpj96ZTW TO /home/ubuntu/.ansible/tmp/ansible-tmp-1569828606.07-4717533724530/AnsiballZ_os_server_action.py <127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/ubuntu/.ansible/tmp/ansible-tmp-1569828606.07-4717533724530/ /home/ubuntu/.ansible/tmp/ansible-tmp-1569828606.07-4717533724530/AnsiballZ_os_server_action.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c '/usr/bin/python /home/ubuntu/.ansible/tmp/ansible-tmp-1569828606.07-4717533724530/AnsiballZ_os_server_action.py && sleep 0' <127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/ubuntu/.ansible/tmp/ansible-tmp-1569828606.07-4717533724530/ > /dev/null 2>&1 && sleep 0' [DEPRECATION WARNING]: Distribution Ubuntu 16.04 on host 127.0.0.1 should use /usr/bin/python3, but is using /usr/bin/python for backward compatibility with prior Ansible releases. A future Ansible release will default to using the discovered platform python for this host. See https://docs.ansible.com/ansible/2.8/reference_appendices/interpreter_discovery.html for more information. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. fatal: [127.0.0.1]: FAILED! => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "msg": "New-style module did not handle its own exit" } PLAY RECAP ********************************************************************************************************************************************************************************** 127.0.0.1 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 ``` There were the same error at the "start" action.
https://github.com/ansible/ansible/issues/62958
https://github.com/ansible/ansible/pull/64330
78e476eb20fc78be7b64f36cb5c518a12a3d482d
42b290b781f0ce6c1cf70c4f02ec5c66a03e6783
2019-09-30T07:39:42Z
python
2019-11-02T08:42:34Z
lib/ansible/modules/cloud/openstack/os_server_action.py
#!/usr/bin/python # coding: utf-8 -*- # Copyright (c) 2015, Jesse Keating <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: os_server_action short_description: Perform actions on Compute Instances from OpenStack extends_documentation_fragment: openstack version_added: "2.0" author: "Jesse Keating (@omgjlk)" description: - Perform server actions on an existing compute instance from OpenStack. This module does not return any data other than changed true/false. When I(action) is 'rebuild', then I(image) parameter is required. options: server: description: - Name or ID of the instance required: true wait: description: - If the module should wait for the instance action to be performed. type: bool default: 'yes' timeout: description: - The amount of time the module should wait for the instance to perform the requested action. default: 180 action: description: - Perform the given action. The lock and unlock actions always return changed as the servers API does not provide lock status. choices: [stop, start, pause, unpause, lock, unlock, suspend, resume, rebuild] default: present image: description: - Image the server should be rebuilt with version_added: "2.3" availability_zone: description: - Ignored. Present for backwards compatibility requirements: - "python >= 2.7" - "openstacksdk" ''' EXAMPLES = ''' # Pauses a compute instance - os_server_action: action: pause auth: auth_url: https://identity.example.com username: admin password: admin project_name: admin server: vm1 timeout: 200 ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs, openstack_cloud_from_module _action_map = {'stop': 'SHUTOFF', 'start': 'ACTIVE', 'pause': 'PAUSED', 'unpause': 'ACTIVE', 'lock': 'ACTIVE', # API doesn't show lock/unlock status 'unlock': 'ACTIVE', 'suspend': 'SUSPENDED', 'resume': 'ACTIVE', 'rebuild': 'ACTIVE'} _admin_actions = ['pause', 'unpause', 'suspend', 'resume', 'lock', 'unlock'] def _action_url(server_id): return '/servers/{server_id}/action'.format(server_id=server_id) def _wait(timeout, cloud, server, action, module, sdk): """Wait for the server to reach the desired state for the given action.""" for count in sdk.utils.iterate_timeout( timeout, "Timeout waiting for server to complete %s" % action): try: server = cloud.get_server(server.id) except Exception: continue if server.status == _action_map[action]: return if server.status == 'ERROR': module.fail_json(msg="Server reached ERROR state while attempting to %s" % action) def _system_state_change(action, status): """Check if system state would change.""" if status == _action_map[action]: return False return True def main(): argument_spec = openstack_full_argument_spec( server=dict(required=True), action=dict(required=True, choices=['stop', 'start', 'pause', 'unpause', 'lock', 'unlock', 'suspend', 'resume', 'rebuild']), image=dict(required=False), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, required_if=[('action', 'rebuild', ['image'])], **module_kwargs) action = module.params['action'] wait = module.params['wait'] timeout = module.params['timeout'] image = module.params['image'] sdk, cloud = openstack_cloud_from_module(module) try: server = cloud.get_server(module.params['server']) if not server: module.fail_json(msg='Could not find server %s' % server) status = server.status if module.check_mode: module.exit_json(changed=_system_state_change(action, status)) if action == 'stop': if not _system_state_change(action, status): module.exit_json(changed=False) cloud.compute.post( _action_url(server.id), json={'os-stop': None}) if wait: _wait(timeout, cloud, server, action, module, sdk) module.exit_json(changed=True) if action == 'start': if not _system_state_change(action, status): module.exit_json(changed=False) cloud.compute.post( _action_url(server.id), json={'os-start': None}) if wait: _wait(timeout, cloud, server, action, module, sdk) module.exit_json(changed=True) if action == 'pause': if not _system_state_change(action, status): module.exit_json(changed=False) cloud.compute.post( _action_url(server.id), json={'pause': None}) if wait: _wait(timeout, cloud, server, action, module, sdk) module.exit_json(changed=True) elif action == 'unpause': if not _system_state_change(action, status): module.exit_json(changed=False) cloud.compute.post( _action_url(server.id), json={'unpause': None}) if wait: _wait(timeout, cloud, server, action, module, sdk) module.exit_json(changed=True) elif action == 'lock': # lock doesn't set a state, just do it cloud.compute.post( _action_url(server.id), json={'lock': None}) module.exit_json(changed=True) elif action == 'unlock': # unlock doesn't set a state, just do it cloud.compute.post( _action_url(server.id), json={'unlock': None}) module.exit_json(changed=True) elif action == 'suspend': if not _system_state_change(action, status): module.exit_json(changed=False) cloud.compute.post( _action_url(server.id), json={'suspend': None}) if wait: _wait(timeout, cloud, server, action, module, sdk) module.exit_json(changed=True) elif action == 'resume': if not _system_state_change(action, status): module.exit_json(changed=False) cloud.compute.post( _action_url(server.id), json={'resume': None}) if wait: _wait(timeout, cloud, server, action, module, sdk) module.exit_json(changed=True) elif action == 'rebuild': image = cloud.get_image(image) if image is None: module.fail_json(msg="Image does not exist") # rebuild doesn't set a state, just do it cloud.compute.post( _action_url(server.id), json={'rebuild': None}) if wait: _wait(timeout, cloud, server, action, module, sdk) module.exit_json(changed=True) except sdk.exceptions.OpenStackCloudException as e: module.fail_json(msg=str(e), extra_data=e.extra_data) if __name__ == '__main__': main()