diff options
Diffstat (limited to 'ansible_collections/infinidat')
47 files changed, 7940 insertions, 0 deletions
diff --git a/ansible_collections/infinidat/infinibox/.gitignore b/ansible_collections/infinidat/infinibox/.gitignore new file mode 100644 index 000000000..bd0ad5f4f --- /dev/null +++ b/ansible_collections/infinidat/infinibox/.gitignore @@ -0,0 +1,112 @@ +vault_password.txt +# build products... +*.py[co] +build +AUTHORS.TXT +# Emacs backup and autosave files... +*~ +.\#* +\#* +# RPM stuff... +MANIFEST +dist +rpm-build +# Eclipse/PyDev stuff... +.project +.pydevproject +# PyCharm stuff... +.idea +#IntelliJ IDEA stuff.. +*.iml +#VSCode stuff.. +.vscode/ +# Mac OS X stuff... +.DS_Store +# manpage build stuff... +docs/man/man1/ansible*.1 +docs/man/man1/ansible*.1.asciidoc.in +docs/man/man3/* +# Sublime stuff +*.sublime-project +*.sublime-workspace +# docsite stuff... +docs/docsite/_build +docs/docsite/*.html +docs/docsite/htmlout +docs/docsite/rst/cli/ansible-*.rst +docs/docsite/rst/cli/ansible.rst +docs/docsite/rst/dev_guide/collections_galaxy_meta.rst +docs/docsite/rst/dev_guide/testing/sanity/index.rst.new +docs/docsite/rst/modules/*.rst +docs/docsite/rst/playbooks_directives.rst +docs/docsite/rst/plugins_by_category.rst +docs/docsite/rst/plugins/*/*.rst +docs/docsite/rst/reference_appendices/config.rst +docs/docsite/rst/reference_appendices/playbooks_keywords.rst +docs/docsite/rst_warnings + without Ansibledocs/docsite/searchindex.js +docs/docsite/_static/*.gif +docs/docsite/_static/*.png +docs/docsite/_static/websupport.js +# deb building stuff... +/debian/ +deb-build +# Vim +Session.vim +*.swp +*.swo + +credentials.yml +# test output +*.retry +*.out +*.gz +.pytest_cache/ +.tox +.cache +.pytest_cache +results.xml +coverage.xml +/test/units/cover-html +/test/integration/targets/*/backup/ +/test/cache/* +# Development +tests/hacking +tests/sanity +/test/develop +venv +Vagrantfile +.vagrant +ansible.egg-info/ +/shippable/ +/test/integration/cloud-config-*.* +!/test/integration/cloud-config-*.*.template +.python-version +# Release directory +packaging/release/ansible_release +/.cache/ +/test/results/ +/test/integration/cloud-config-aws.yml +/test/integration/inventory.networking +/test/integration/inventory.winrm +/test/integration/cloud-config-aws.yml +/test/integration/cloud-config-cs.ini +# python 'rope' stuff +.ropeproject +# local 'ack' config files +.ackrc +# default 'coverage html' results +htmlcov/ +# default 'coverage' tool data +.coverage +# ansible-test coverage results +test/units/.coverage.* +/test/integration/cloud-config-azure.yml +/SYMLINK_CACHE.json +changelogs/.plugin-cache.yaml +.ansible-test-timeout.json +# ansible-test temporary metadata file for use with delgation +/metadata-*.json +# secrets +ibox_vars/*.yaml +collections/ diff --git a/ansible_collections/infinidat/infinibox/.gitlab-ci.yml b/ansible_collections/infinidat/infinibox/.gitlab-ci.yml new file mode 100644 index 000000000..013f6976b --- /dev/null +++ b/ansible_collections/infinidat/infinibox/.gitlab-ci.yml @@ -0,0 +1,70 @@ +--- +# Ref: https://docs.gitlab.com/ce/ci/yaml/README.html + +# CICD environment variables: +# - VAULT_PASSWORD_FILE +# - Type: File +# - Key: VAULT_PASSWORD_FILE +# - Value: <ansible vault password for the vars file for the ibox specified in --extra-vars> +# - i.e. The password that allows one to view the file using "ansible-vault view <file>" + +image: psusdev/gitlab-cicd:v0.14 + +playbook_testing: + stage: test + script: + # Disable index-url = https://pypi.infinidat.com/simple. + - mv ~/.pip/pip.conf ~/.pip/pip.conf.notused || true + - python3 -m venv venv + - . ./venv/bin/activate + - python --version + - export PIP_REQUIRE_VIRTUALENV=true + - python -m pip install --upgrade pip + - pip install -r requirements.txt + - pip install -r requirements-dev.txt + - echo "Requirements dump:" + - pip freeze + - echo + - echo "Tested ansible version -> $(ansible --version)" + + # Build and install ansible collection. Find collection version from yml, strip quotes. + - coll_version=$(spruce json galaxy.yml | jq '.version' | sed 's?"??g') + - coll_namespace=$(spruce json galaxy.yml | jq '.namespace' | sed 's?"??g') + - coll_name=$(spruce json galaxy.yml | jq '.name' | sed 's?"??g') + - echo "Collection version -> ${coll_version}" + - echo "Collection namespace -> ${coll_namespace}" + - echo "Collection name -> ${coll_name}" # gitlab's cilint does not like a colon here + - echo "Collection tarball -> ${coll_namespace}-${coll_name}-${coll_version}.tar.gz" + - ansible-galaxy collection build + - ansible-galaxy collection install "${coll_namespace}-${coll_name}-${coll_version}.tar.gz" -vvv + # -p ./test_collection + + # Run testing playbooks + - git_project="ansible-infinidat-collection" + - echo "$git_project commit -> $(git log --max-count=1 --oneline)" + - pushd ./playbooks > /dev/null + - export ANSIBLE_CONFIG="/builds/PSUS/$git_project/playbooks/ansible.cfg" + - export ANSIBLE_FORCE_COLOR=true + - ibox_extra_vars="@../ibox_vars/iboxCICD.yaml" + - verbosity="-v" + - ansible-playbook --extra-vars "$ibox_extra_vars" --vault-password-file "$VAULT_PASSWORD_FILE" test_create_resources.yml "${verbosity}" + - ansible-playbook --extra-vars "$ibox_extra_vars" --vault-password-file "$VAULT_PASSWORD_FILE" test_remove_resources.yml "${verbosity}" + - popd > /dev/null + + # Show summery of execution tasks + - ./bin/test_summarize.sh general + + # Run testing map cluster playbooks + - git_project="ansible-infinidat-collection" + - echo "$git_project commit -> $(git log --max-count=1 --oneline)" + - pushd ./playbooks > /dev/null + - export ANSIBLE_CONFIG="/builds/PSUS/$git_project/playbooks/ansible.cfg" + - export ANSIBLE_FORCE_COLOR=true + - ibox_extra_vars="@../ibox_vars/iboxCICD.yaml" + - verbosity="-v" + - ansible-playbook --extra-vars "$ibox_extra_vars" --vault-password-file "$VAULT_PASSWORD_FILE" test_create_map_cluster.yml "${verbosity}" + - ansible-playbook --extra-vars "$ibox_extra_vars" --vault-password-file "$VAULT_PASSWORD_FILE" test_remove_map_cluster.yml "${verbosity}" + - popd > /dev/null + + # Show summery of execution tasks + - ./bin/test_summarize.sh map-cluster diff --git a/ansible_collections/infinidat/infinibox/CHANGELOG.rst b/ansible_collections/infinidat/infinibox/CHANGELOG.rst new file mode 100644 index 000000000..482aa5b52 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/CHANGELOG.rst @@ -0,0 +1,88 @@ +========== +Change Log +========== + +------------------- +v1.3.12 (2022-12-04) +------------------- + +^^^^^^^^^ +Bug Fixes +^^^^^^^^^ +* Fix infini_vol's write_protected field handling. + +------------------- +v1.3.11 (2022-12-03) +------------------- + +^^^^^^^^^^^^^^^^^^^^ +Feature Enhancements +^^^^^^^^^^^^^^^^^^^^ +* Fix module sanity errors not flagged when run locally, but flagged when uploaded to the automation hub for certification. + +-------------------- +v1.3.10 (2022-12-03) +-------------------- + +^^^^^^^^^^^^^^^^^^^^ +Feature Enhancements +^^^^^^^^^^^^^^^^^^^^ +* Add documentation for the delta-time filter. The delta-time filter is used in test_create_resources.yml playbook. + +------------------- +v1.3.9 (2022-12-02) +------------------- + +^^^^^^^^^^^^^^^^^^^^ +Feature Enhancements +^^^^^^^^^^^^^^^^^^^^ +* Fix module sanity errors not flagged when run locally, but flagged when uploaded to the automation hub for certification. + +------------------- +v1.3.8 (2022-12-01) +------------------- + +^^^^^^^^^^^^^^^^^^^^ +Feature Enhancements +^^^^^^^^^^^^^^^^^^^^ +* Support thin and thick provisioning in infini_fs. +* Refactor module imports. +* In the test_create_resources.yml and test_remove_resources.yml example playbooks, run rescan-scsi-bus.sh on host. + +^^^^^^^^^ +Bug Fixes +^^^^^^^^^ +* Fix infini_vol stat state. Return the provisioning type (thin or thick) properly. + +------------------- +v1.3.7 (2022-10-03) +------------------- + +^^^^^^^^^^^^^^^^^^^^ +Project Enhancements +^^^^^^^^^^^^^^^^^^^^ +* Execute and pass `Ansible Sanity Tests <https://docs.ansible.com/ansible/devel/dev_guide/developing_collections_testing.html#testing-tools>`_. This is in preparation for Ansible Automation Hub (AAH) certification. +* No longer pin module versions in requirements.txt. Record module versions used while testing within CICD using pip freeze. + +^^^^^^^^^^^^^^^^^^^^ +Feature Enhancements +^^^^^^^^^^^^^^^^^^^^ +* Add volume restore to infini_vol. + +^^^^^^^^^^^ +New Modules +^^^^^^^^^^^ +* infini_cluster: Create, delete and modify host clusters on an Infinibox. +* infini_network_space: Create, delete and modify network spaces on an Infinibox. + +^^^^^^^^^^^^^ +New Playbooks +^^^^^^^^^^^^^ +* infinisafe_demo_runtest.yml +* infinisafe_demo_setup.yml +* infinisafe_demo_teardown.yml + +^^^^^^^^^ +Bug Fixes +^^^^^^^^^ +* Fix collection path to module_utils when importing utility modules. diff --git a/ansible_collections/infinidat/infinibox/FILES.json b/ansible_collections/infinidat/infinibox/FILES.json new file mode 100644 index 000000000..5f99555df --- /dev/null +++ b/ansible_collections/infinidat/infinibox/FILES.json @@ -0,0 +1,425 @@ +{ + "files": [ + { + "name": ".", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "docs", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "docs/DEV_README.md", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "793740dc81e2ab5861a5c026ec227f40b63eb8b71a5d8ba608cc9c16a9640723", + "format": 1 + }, + { + "name": "tests", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/sanity", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.10.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "tests/hacking", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/hacking/infini_vol_present_example.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "23e4089f3d750800a7c782a3d579a53f298d366f0b1f84431a02414c12b81160", + "format": 1 + }, + { + "name": "meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "meta/execution-environment.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8b03e59e1cf4341741306b8d290961e3295a92e7810c0028bb401f2ae1eca745", + "format": 1 + }, + { + "name": "meta/runtime.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a64562102c20fa61d7e538a3868d082f7aa20e32bc3bbccfba7e1dda5da45947", + "format": 1 + }, + { + "name": "bin", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "Makefile", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "50951adfabb9adde022b27b189197b0b2064f35c330d4fa24889c616932404f0", + "format": 1 + }, + { + "name": "README.md", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "53fccfe2fb4c05ec005e5fcd3ed0f539cd8ba8258a972e1d082cd3f23d4f463d", + "format": 1 + }, + { + "name": ".gitlab-ci.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "55ffc971ac57019980f0d6b9748ba0630548afe86d548e950cd952cfd67fd2cf", + "format": 1 + }, + { + "name": "ibox_vars", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "ibox_vars/iboxCICD.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c5e5ea378ed20e66e96c3fafee6c53845ed534c27804ee82ccdeca7edb23d8e5", + "format": 1 + }, + { + "name": "ibox_vars/iboxNNNN_example.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "97812c7706f088a4b0f926a7fee966c20ed788fa5ec42814e4f94d2ba66404f8", + "format": 1 + }, + { + "name": "Makefile-help", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1c1bf806cc1b36461f41ce8993811ee8c4defa0d39c8fbf471236722482e396e", + "format": 1 + }, + { + "name": "playbooks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/test_remove_network_spaces.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "567cc99c829f63ac287e80550884a4698f9c80210eece857150203d8320b57fe", + "format": 1 + }, + { + "name": "playbooks/infinisafe_demo_runtest.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "d9b28566237125f820184a36c653281312717e5747c97d95ccf3fc13054739a1", + "format": 1 + }, + { + "name": "playbooks/test_create_snapshots.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a1a29f53a43d35dc13e144bd85ac69eec0513621d869c24c9765f1491b1e2e77", + "format": 1 + }, + { + "name": "playbooks/test_remove_snapshots.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c1847ecb16b3a825ab494a8e992323c63940e9c0f6b9fb705a17e90393b2645d", + "format": 1 + }, + { + "name": "playbooks/infinisafe_demo_setup.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "08e1b350fed21d7dc483e9f5993bb067ee81ac7a4b3385eac75e9e7ae0149ccb", + "format": 1 + }, + { + "name": "playbooks/test_create_network_spaces.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a31ec0f9cd1da16136398b3f860b8ca008945e679475b712a3cbfd09ccdaffe5", + "format": 1 + }, + { + "name": "playbooks/test_create_map_cluster.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "87c95887ad3422b6edf744f462a68437c27315f39539e13af7a8186e8631050d", + "format": 1 + }, + { + "name": "playbooks/inventory", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "93d1758720c0534d6c7902f91dd6dc14b1e429b24f330f5903267910d43c50b4", + "format": 1 + }, + { + "name": "playbooks/test_create_resources.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4f02dc52aa3ac47820454ff2785e913d5d12bab13f7402111a8b2985d8ea09b3", + "format": 1 + }, + { + "name": "playbooks/infinisafe_demo_teardown.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f4692d6ddc56c3dbc867e8050a7d5c3faffc7be87bcf22ef4c1476deca9e1a5e", + "format": 1 + }, + { + "name": "playbooks/ansible.cfg", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6946120d2926bdde34018f3507e119c2e5f7d08e74ab25fe42e9ab61c7d07e62", + "format": 1 + }, + { + "name": "playbooks/test_remove_map_cluster.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "576591f3fd874080e7b233231204cf1fbfb89776d1ae0fc645b74c69f686cdf8", + "format": 1 + }, + { + "name": "playbooks/test_remove_resources.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9ac5c717f23ddd5a6553ef4d3fb9a6f89b78bd6977dcc120842d3315f0ec2018", + "format": 1 + }, + { + "name": "CHANGELOG.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "305df25a3023d0c38d95beea1b98d819a86aabda96be05b08d3b23dbf0530d6d", + "format": 1 + }, + { + "name": "plugins", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/modules/infini_fs.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3d6dd884674f25dcafaf90b8de0e68db49afd8bff874b74d014988382b508c3d", + "format": 1 + }, + { + "name": "plugins/modules/infini_port.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "464597d73393c954f79b89aeb5cd43724f780b5dcb1d7925808ace7ed9d1ade7", + "format": 1 + }, + { + "name": "plugins/modules/infini_map.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a709dd42075d2b37cef00dff8a3fdbc3107fd6da5847fd69bc8cebb36445412f", + "format": 1 + }, + { + "name": "plugins/modules/infini_network_space.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4f6a141ab5e8a9bd89d90d9d90dba7e1b6a491f9b427107f0052e3a6a3972001", + "format": 1 + }, + { + "name": "plugins/modules/infini_vol.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9a92b8184d6cdbc4d6440a517bb51a288a90b54c392a4ce2ef4d5d4a4a4a9057", + "format": 1 + }, + { + "name": "plugins/modules/infini_export_client.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "dfc2c3af83c2356754e239d4bce24cb509dcf057864cf15f6083fe8b9ca070b9", + "format": 1 + }, + { + "name": "plugins/modules/infini_pool.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3e24f22b08d7778dd9394cfc53afa453c97dfd5bd555451c137a0083b666c85b", + "format": 1 + }, + { + "name": "plugins/modules/infini_cluster.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2ca78b1585c6395834647ced906c49ea160922de7659e993b3bf2a67fa590728", + "format": 1 + }, + { + "name": "plugins/modules/infini_host.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8fe8d1ceff823d19bd703fe9690fd3c28ffd3c118ad79d2a57e1b00d9c1ed294", + "format": 1 + }, + { + "name": "plugins/modules/infini_export.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e476bdf871ee10af8aac8909fdcffb4c10739483e94268ad5906039a9dc118c4", + "format": 1 + }, + { + "name": "plugins/modules/infini_user.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "10bb0e644545ad216fff1db8cd9952d65941dcfdfcd6da3536513434baa7351b", + "format": 1 + }, + { + "name": "plugins/modules/__init__.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "plugins/filter", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/filter/delta_time.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8d8fd570aa879ec7e5436d9981eb561e8fea5b30d12def6767043b0a25909506", + "format": 1 + }, + { + "name": "plugins/filter/psus_filters.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0f88020170134ef6e22aeeeb2c72eeb36427817027b2fd7a6143ea76355690a4", + "format": 1 + }, + { + "name": "plugins/doc_fragments", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/doc_fragments/infinibox.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3e25f04ed34bd1678dd7e22073f44c5dab1e063a0f588b7160e3abcfa2489629", + "format": 1 + }, + { + "name": "plugins/module_utils", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/module_utils/infinibox.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b47754c0c5c2afccafcca852386186b223c36b6d801c62a2607a249918f49a6f", + "format": 1 + }, + { + "name": "requirements.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "62f18d0b71e237e6ce05c76a970a709c43d962fa43f8a6801b7772c8ae1b4a05", + "format": 1 + }, + { + "name": "requirements-dev.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "84259416e2286c6f6747c6eda6c943370b904e6cc98b3a4c350a38ecddf3db13", + "format": 1 + }, + { + "name": "test-args", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".gitignore", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "acc90aac40128d0adf5d3a48fb2b5d770a18d5b4ec5d7df499f0018e6453ed36", + "format": 1 + }, + { + "name": "LICENSE", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e77edcc69dd86480e3392a71e6be429cb9576ed59e49bbb2e9dac4a44b28068f", + "format": 1 + } + ], + "format": 1 +}
\ No newline at end of file diff --git a/ansible_collections/infinidat/infinibox/LICENSE b/ansible_collections/infinidat/infinibox/LICENSE new file mode 100644 index 000000000..097fffa85 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/LICENSE @@ -0,0 +1,202 @@ +Copyright 2020 Infinidat, Inc. + +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/> + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + +<one line to give the program's name and a brief idea of what it does.> +Copyright (C) <year> <name of author> + +This program 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. + +This program 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 program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + +<program> Copyright (C) <year> <name of author> +This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. +This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>. + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/ licenses/why-not-lgpl.html>. diff --git a/ansible_collections/infinidat/infinibox/MANIFEST.json b/ansible_collections/infinidat/infinibox/MANIFEST.json new file mode 100644 index 000000000..87d69d95d --- /dev/null +++ b/ansible_collections/infinidat/infinibox/MANIFEST.json @@ -0,0 +1,51 @@ +{ + "collection_info": { + "namespace": "infinidat", + "name": "infinibox", + "version": "1.3.12", + "authors": [ + "Infinidat <partners.infi@infinidat.com>", + "David Ohlemacher", + "Gregory Shulov" + ], + "readme": "README.md", + "tags": [ + "array", + "cloud", + "fiber", + "fiber_channel", + "fiberchannel", + "hostpowertools", + "ibox", + "infinibox", + "infinidat", + "infinihost", + "infinisdk", + "iscsi", + "nas", + "nfs", + "san", + "storage", + "storage_array", + "storagearray" + ], + "description": "A set of Ansible modules that allow simple, but powerful, idempotent interactions with Infinidat InfiniBoxes.", + "license": [ + "GPL-3.0-or-later" + ], + "license_file": null, + "dependencies": {}, + "repository": "https://www.github.com/infinidat/ansible-infinidat-collection", + "documentation": null, + "homepage": null, + "issues": "https://www.github.com/infinidat/ansible-infinidat-collection/issues" + }, + "file_manifest_file": { + "name": "FILES.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "71d6d4e9dd13ffdc2e4aa2b21b5b1412b43c85b9be7c5c19d0231734caa025cd", + "format": 1 + }, + "format": 1 +}
\ No newline at end of file diff --git a/ansible_collections/infinidat/infinibox/Makefile b/ansible_collections/infinidat/infinibox/Makefile new file mode 100644 index 000000000..0be78fdd6 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/Makefile @@ -0,0 +1,333 @@ +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +# vim: set foldmethod=indent foldnestmax=1 foldcolumn=1: + +# A Makefile for creating, running and testing Infindat's Ansible collection. + +### Dependencies ### +# - jq: https://stedolan.github.io/jq/ +# - spruce: https://github.com/geofffranks/spruce + +### environment ### +# Include an env file with secrets. This exposes the secrets +# as envvars only for the life of make. It does not +# pollute the environment persistently. +# Format: +# API_KEY=someAnsibleGalaxyApiKey +# The key only needs to be valid to use target galaxy-colletion-publish. + +_env = ~/.ssh/ansible-galaxy.sh +include $(_env) +export $(shell sed 's/=.*//' $(_env)) + +# Use color in Makefiles. +_use_color = true + +include Makefile-help + +### Vars ### +_version = $(shell spruce json galaxy.yml | jq '.version' | sed 's?"??g') +_namespace = $(shell spruce json galaxy.yml | jq '.namespace' | sed 's?"??g') +_name = $(shell spruce json galaxy.yml | jq '.name' | sed 's?"??g') +_install_path = ~/.ansible/collections +_install_path_local = $$HOME/.ansible/collections +_python_version = python3.8 +_venv = venv +_requirements-file = requirements.txt +_requirements-dev-file = requirements-dev.txt +_user = psus-gitlab-cicd +_password_file = vault_password +_password = $$(cat vault_password.txt) +_ibox_url = ibox1521 +_infinishell_creds = --user $(_user) --password $(_password) $(_ibox_url) +SHELL = /bin/bash +_ansible_clone = ~/cloud/ansible +_network_space_ips = 172.31.32.145 172.31.32.146 172.31.32.147 172.31.32.148 172.31.32.149 172.31.32.150 +_modules = "infini_cluster.py" "infini_export.py" "infini_host.py" "infini_network_space.py" "infini_port.py" "infini_vol.py" "infini_export_client.py" "infini_fs.py" "infini_map.py" "infini_pool.py" "infini_user.py" + +##@ General +create-venv: ## Setup venv. + $(_python_version) -m venv $(_venv) && \ + source $(_venv)/bin/activate && \ + python -m pip install --upgrade pip && \ + python -m pip install --upgrade --requirement $(_requirements-file) + python -m pip install --upgrade --requirement $(_requirements-dev-file) + +_check-vars: +ifeq ($(strip $(API_KEY)),) + @echo "API_KEY variable is unset" && false +endif + +env-show: _check-vars + @echo "API_KEY=[ set but redacted ]" + +version: _check-vars ## Show versions. + @echo -e $(_begin) + ansible --version + @echo + ansible-galaxy collection list + @echo -e $(_finish) + +_test-venv: + @# Test that a venv is activated +ifndef VIRTUAL_ENV + @echo "Error: Virtual environment not set" + @echo -e "\nRun:\n make pyvenv" + @echo -e " source $(_venv)/bin/activate\n" + exit 1 +endif + @echo "Virtual environment set" + +pylint: + @echo -e $(_begin) + cd plugins/modules && \ + pylint infini_network_space.py + cd - + @echo -e $(_finish) + +pyfind: ## Search project python files using: f='search term' make pyfind + find . -name "*.py" | xargs grep -n "$$f" | egrep -v 'venv|eggs|parts|\.git|external-projects|build' + +##@ Galaxy + +galaxy-collection-build: ## Build the collection. + @echo -e $(_begin) + rm -rf collections/ + ansible-galaxy collection build + @echo -e $(_finish) + +galaxy-collection-build-force: ## Force build the collection. Overwrite an existing collection file. + @echo -e $(_begin) + ansible-galaxy collection build --force + @echo -e $(_finish) + +galaxy-collection-publish: _check-vars ## Publish the collection to https://galaxy.ansible.com/ using the API key provided. + @echo -e $(_begin) + ansible-galaxy collection publish --api-key $(API_KEY) ./$(_namespace)-$(_name)-$(_version).tar.gz -vvv + @echo -e $(_finish) + +galaxy-collection-install: ## Download and install from galaxy.ansible.com. This will wipe $(_install_path). + @echo -e $(_begin) + ansible-galaxy collection install $(_namespace).$(_name) --collections-path $(_install_path) --force + @echo -e $(_finish) + +galaxy-collection-install-locally: ## Download and install from local tar file. + @echo -e $(_begin) + ansible-galaxy collection install --force $(_namespace)-$(_name)-$(_version).tar.gz --collections-path $(_install_path_local) + @echo -e $(_finish) + +##@ Playbooks Testing +_test_playbook: + @# Run a playbook specified by an envvar. + @# See DEV_README.md + @# vault_pass env var must be exported. + cd playbooks && \ + export ANSIBLE_LIBRARY=/home/dohlemacher/cloud/ansible-infinidat-collection/playbooks/plugins/modules; \ + export ANSIBLE_MODULE_UTILS=/home/dohlemacher/cloud/ansible-infinidat-collection/plugins/module_utils; \ + if [ ! -e "../vault_password.txt" ]; then \ + echo "Please add your vault password to vault_password.txt"; \ + exit 1; \ + fi; \ + ansible-playbook \ + $$ask_become_pass \ + --inventory "inventory" \ + --extra-vars "@../ibox_vars/iboxCICD.yaml" \ + --vault-password-file ../vault_password.txt \ + "$$playbook_name"; \ + cd - + +test-create-resources: ## Run full creation test suite as run by Gitlab CICD. + @echo -e $(_begin) + ask_become_pass="-K" playbook_name=test_create_resources.yml $(_make) _test_playbook + @echo -e $(_finish) + +test-remove-resources: ## Run full removal test suite as run by Gitlab CICD. + @echo -e $(_begin) + ask_become_pass="-K" playbook_name=test_remove_resources.yml $(_make) _test_playbook + @echo -e $(_finish) + +test-create-snapshots: ## Test creating immutable snapshots. + @echo -e $(_begin) + playbook_name=test_create_snapshots.yml $(_make) _test_playbook + @echo -e $(_finish) + +test-remove-snapshots: ## Test removing immutable snapshots (teardown). + @echo -e $(_begin) + playbook_name=test_remove_snapshots.yml $(_make) _test_playbook + @echo -e $(_finish) + +test-create-net-spaces: dev-install-modules-to-local-collection ## Test creating network spaces. + @echo -e $(_begin) + playbook_name=test_create_network_spaces.yml $(_make) _test_playbook + @echo -e $(_finish) + +test-remove-net-spaces: ## Test removing net spaces (teardown). + @echo -e $(_begin) + playbook_name=test_remove_network_spaces.yml $(_make) _test_playbook + @echo -e $(_finish) + +test-create-map-cluster: ## Run full creation test suite as run by Gitlab CICD. + @echo -e $(_begin) + playbook_name=test_create_map_cluster.yml $(_make) _test_playbook + @echo -e $(_finish) + +test-remove-map-cluster: ## Run full removal test suite as run by Gitlab CICD. + @echo -e $(_begin) + playbook_name=test_remove_map_cluster.yml $(_make) _test_playbook + @echo -e $(_finish) + +##@ Infinisafe Demo + +infinisafe-demo-setup: ## Setup infinisafe demo. + @echo -e $(_begin) + playbook_name=infinisafe_demo_setup.yml $(_make) _test_playbook + @echo -e $(_finish) + +infinisafe-demo-runtest: ## Run tests on infinisafe demo snapshot on forensics host. + @echo -e $(_begin) + ask_become_pass="-K" playbook_name=infinisafe_demo_runtest.yml $(_make) _test_playbook + @echo -e $(_finish) + +infinisafe-demo-teardown: ## Teardown infinisafe demo. + @echo -e $(_begin) + ask_become_pass="-K" playbook_name=infinisafe_demo_teardown.yml $(_make) _test_playbook + @echo -e $(_finish) + +##@ Hacking +#_module_under_test = infini_network_space +_module_under_test = infini_fs + +dev-hack-create-links: ## Create soft links inside an Ansible clone to allow module hacking. + @#echo "Creating hacking module links" + @for m in $(_modules); do \ + ln --force --symbolic $$(pwd)/plugins/modules/$$m $(_ansible_clone)/lib/ansible/modules/infi/$$m; \ + done + @#echo "Creating hacking module_utils links $(_module_utilities)" + @for m in "infinibox.py" "iboxbase.py"; do \ + ln --force --symbolic $$(pwd)/plugins/module_utils//$$m $(_ansible_clone)/lib/ansible/module_utils/$$m; \ + done + +_dev-hack-module: dev-hack-create-links # Run module. PDB is available using breakpoint(). + cwd=$$(pwd) && \ + cd $(_ansible_clone) && \ + JSON_IN="$$cwd/tests/hacking/$(_module_under_test)_$${state}.json" && \ + if [[ ! -a "$$JSON_IN" ]]; then \ + >&2 echo "Error: $$JSON_IN not found"; \ + exit; \ + fi; \ + source venv/bin/activate 1> /dev/null 2> /dev/null && \ + source hacking/env-setup 1> /dev/null 2> /dev/null && \ + AIC=/home/dohlemacher/cloud/ansible-infinidat-collection \ + ANS=/home/dohlemacher/cloud/ansible \ + PYTHONPATH="$$PYTHONPATH:$$AIC/plugins/modules" \ + PYTHONPATH="$$PYTHONPATH:$$AIC/plugins/module_utils" \ + PYTHONPATH="$$PYTHONPATH:$$ANS/lib" \ + PYTHONPATH="$$PYTHONPATH:$$ANS/hacking/build_library/build_ansible" \ + PYTHONPATH="$$PYTHONPATH:$$ANS/venv/lib/python3.8/site-packages" \ + python -m "$(_module_under_test)" "$$JSON_IN" 2>&1 | \ + grep -v 'Unverified HTTPS request' + +_dev-hack-module-jq: # If module is running to the point of returning json, use this to run it and prettyprint using jq. + @$(_make) _dev-hack-module | egrep 'changed|failed' | jq '.' + +dev-hack-module-stat: ## Hack stat. + @state=stat $(_make) _dev-hack-module + +dev-hack-module-stat-jq: ## Hack stat with jq. + @state=stat $(_make) _dev-hack-module-jq + +dev-hack-module-present: ## Hack present. + @state=present $(_make) _dev-hack-module + +dev-hack-module-present-jq: ## Hack present with jq. + @state=present $(_make) _dev-hack-module-jq + +dev-hack-module-absent: ## Hack absent. + @state=absent $(_make) _dev-hack-module + +dev-hack-module-absent-jq: ## Hack absent with jq. + @state=absent $(_make) _dev-hack-module-jq + +##@ Test Module +_module = infini_network_space.py + +find-default-module-path: ## Find module path. + ansible-config list | spruce json | jq '.DEFAULT_MODULE_PATH.default' | sed 's?"??g' + +_collection_local_path = ~/.ansible/collections/ansible_collections/infinidat/infinibox/plugins +dev-install-modules-to-local-collection: ## Copy modules to local collection + @echo -e $(_begin) + @echo "local collection path: $(_collection_local_path)" + @echo "Installing modules locally" + @cp plugins/modules/*.py $(_collection_local_path)/modules + @echo "Installing utilities locally" + @cp plugins/module_utils/*.py $(_collection_local_path)/module_utils + @echo "Installing filters locally" + @cp plugins/filter/*.py $(_collection_local_path)/filter + @echo -e $(_finish) + +##@ ansible-test +test-sanity: ## Run ansible sanity tests + @# in accordance with + @# https://docs.ansible.com/ansible/devel/dev_guide/developing_collections.html#testing-collections + @# This runs on an collection installed from galaxy. This makes it + @# somewhat useless for dev and debugging. Use target test-sanity-locally. + cd $(_install_path)/ansible_collections/infinidat/infinibox && \ + ansible-test sanity --docker default -v + +_setup-sanity-locally: galaxy-collection-build-force galaxy-collection-install-locally + @# Setup a test env. + cd $(_install_path_local)/ansible_collections/infinidat/infinibox && \ + $(_python_version) -m venv $(_venv) && \ + source $(_venv)/bin/activate && \ + python -m pip install --upgrade pip && \ + python -m pip install --upgrade --requirement $(_requirements-file) + +test-sanity-locally: _setup-sanity-locally ## Run ansible sanity tests locally. + @# in accordance with + @# https://docs.ansible.com/ansible/devel/dev_guide/developing_collections.html#testing-collections + @# This runs on an collection installed locally making it useful for dev and debugging. + cd $(_install_path_local)/ansible_collections/infinidat/infinibox && \ + ansible-test sanity --docker default --requirements $(_requirements-file) + +test-sanity-locally-all: galaxy-collection-build-force galaxy-collection-install-locally test-sanity-locally ## Run all sanity tests locally. + @# Run local build, install and sanity test. + @# Note that this will wipe $(_install_path_local). + @echo "test-sanity-locally-all completed" + +##@ IBox +infinishell: ## Run infinishell. + @TERM=xterm infinishell $(_infinishell_creds) --json + +infinishell-events: # Run infinishell with hint to watch events. + @TERM=xterm echo "Command: event.watch username=$(_user) exclude=USER_LOGGED_OUT,USER_LOGIN_SUCCESS,USER_SESSION_EXPIRED,USER_LOGIN_FAILURE tail_length=35" + @TERM=xterm infinishell $(_infinishell_creds) + +infinishell-network-space-iscsi-create: ## Create a network space using infinishell. + @echo -e $(_begin) + @TERM=xterm infinishell --cmd="config.net_space.create name=iSCSI service=iSCSI interface=PG1 network=172.31.32.0/19 -y" $(_infinishell_creds) 2>&1 \ + | egrep 'created|already exists' && \ + for ip in $(_network_space_ips); do \ + echo "Creating IP $$ip" && \ + TERM=xterm infinishell --cmd="config.net_space.ip.create net_space=iSCSI ip_address=$$ip -y" $(_infinishell_creds) 2>&1 \ + | egrep 'created|NET_SPACE_ADDRESS_CONFLICT' && \ + echo "Enabling IP $$ip"; \ + done + @echo -e $(_finish) + +infinishell-network-space-iscsi-delete: ## Delete a network space using infinishell. + @echo -e $(_begin) + @for ip in $(_network_space_ips); do \ + echo "Disabling IP $$ip" && \ + TERM=xterm infinishell --cmd="config.net_space.ip.disable net_space=iSCSI ip_address=$$ip -y" $(_infinishell_creds) 2>&1 \ + | egrep 'disabled|IP_ADDRESS_ALREADY_DISABLED|no such IP address|No such network space' && \ + echo "Deleting IP $$ip" && \ + TERM=xterm infinishell --cmd="config.net_space.ip.delete net_space=iSCSI ip_address=$$ip -y" $(_infinishell_creds) 2>&1 \ + | egrep '$$ip deleted|no such IP address|No such network space'; \ + done + @echo + @echo "Deleting network space iSCSI" && \ + TERM=xterm infinishell --cmd="config.net_space.delete net_space=iSCSI -y" $(_infinishell_creds) 2>&1 \ + | egrep 'deleted|No such network space'; + @echo -e $(_finish) diff --git a/ansible_collections/infinidat/infinibox/Makefile-help b/ansible_collections/infinidat/infinibox/Makefile-help new file mode 100644 index 000000000..ff6914eab --- /dev/null +++ b/ansible_collections/infinidat/infinibox/Makefile-help @@ -0,0 +1,82 @@ +# ##@ Help Group Name +# .PHONY: recipe_name +# To pick up the recipe name, use: +# recipe_name: ## Recipe help. +# @echo -e $(_begin) +# ...works... +# @echo -e $(_finish) + +# Use color in Makefiles. +_USE_COLOR ?= true + +.DEFAULT_GOAL := help + +# Color vars +_help_padding = 30 +_black = \033[0;30m +_red = \033[0;31m +_green = \033[0;32m +_orange = \033[0;33m +_blue = \033[0;34m +_purple = \033[0;35m +_cyan = \033[0;36m +_lt_gray = \033[0;37m +_gray = \033[1;30m +_lt_rd = \033[1;31m +_lt_green = \033[1;32m +_yellow = \033[1;33m +_lt_blue = \033[1;34m +_lt_purple= \033[1;35m +_lt_cyan = \033[1;36m +_white = \033[1;37m +_reset = \033[0m + +# Customize colors for 'make help' +_group = $(_lt_blue) +_recipe = $(_orange) +# Customize colors for make leaders/followers +_heading = $(_yellow) + +# Use _make to execute make with consistent options +_make = make --no-print-directory +_watch = watch -n 1 --no-title + +# Other vars +_LEADER = "================ [" +_FOLLOWER = "\] ================" + +ifneq ($(_USE_COLOR),true) + # No color + _group = + _recipe = + _heading = + _reset = +endif + +_begin = "$(_heading)$(_LEADER) Begin $@ $(_FOLLOWER)$(_reset)" +_finish = "$(_heading)$(_LEADER) Completed $@ $(_FOLLOWER)$(_reset)" + +##@ General +.PHONY: help +help: ## Display this help. + @echo "$(_purpose)" + @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make $(_recipe)<recipe>$(_reset)\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf "$(_recipe)%-$(_help_padding)s$(_reset) %s\n", $$1, $$2 } /^##@/ { printf "\n$(_group)%s$(_reset)\n", substr($$0, 5) } ' $(MAKEFILE_LIST) + +.PHONY: color-help +color-help: ## Edit Makefile-help to change color schemes. + @echo -e $(_begin) + @echo "To enable colors in make output, 'export _USE_COLOR=true' with the leading underscore" + @echo "Edit Makefile-help to change color schemes" +ifeq ($(_USE_COLOR),true) + @printf "\n\tColor is currently enabled\n\n" +else + @printf "\n\tColor is currently disabled\n\n" +endif + @echo -e $(_finish) + +_find_ignore=.git|test|log +.PHONY: ansfind +ansfind: ## Search project files using: f='search term' make ansfind + @echo -e $(_begin) + find . -name "*" -type=f | xargs grep -n "$$f" | egrep -v '$(_find_ignore)' + @echo -e $(_finish) diff --git a/ansible_collections/infinidat/infinibox/README.md b/ansible_collections/infinidat/infinibox/README.md new file mode 100644 index 000000000..b4bb06c90 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/README.md @@ -0,0 +1,78 @@ +# Infinidat's Ansible Collection + +## Platforms Supported +All Infindat InfiniBoxes are supported. + +## Prerequisites +- Ansible 2.12 or newer +- InfiniSDK 151.1.1 or newer. + +## Modules +- infini_cluster: Creates, deletes or modifies host clusters. +- infini_export_client: Creates, deletes or modifys NFS client(s) for existing exports. +- infini_export: Creates, deletes or modifies NFS exports. +- infini_fs: Creates, deletes or modifies filesystems. +- infini_host: Creates, deletes or modifies hosts. +- infini_map: Creates or deletes mappings of volumes to hosts. +- infini_pool: Creates, deletes or modifies pools. +- infini_port: Adds or deletes fiber channel or iSCSI ports to hosts. +- infini_user: Creates, deletes or modifies an InfiniBox user. +- infini_vol: Creates, deletes or modifies a volume. + +Most modules also implement a "stat" state. This is used to gather information, aka status, for the resource without making any changes to it. + +## Installation +Install the Infinidat Ansible collection on hosts or within containers using: +`ansible-galaxy collection install infinidat.infibox -p ~/.ansible/collections` + +Complete instructions for installing collections is available at https://docs.ansible.com/ansible/latest/user_guide/collections_using.html. + +Ansible 2.9 or newer is required to install as a collection. That said, the collection is a tarball. Modules may be extracted and installed manually if use of an older version of Ansible is required. Adjust values in playbooks/ansible.cfg as required. + +## Usage +A Makefile is provided. To see the recipes available within it use `make help`. + +Example playbooks are included in the collection: + +- Main test playbooks: + - test_create_resources.yml: A playbook that creates many resources. It also creates resources again to test idempotency. + - test_remove_resources.yml: A playbook that in the end removes the resources created in the test_create_resources playbook. It too will test idempotency by removing resources again. + +- Playbooks for testing cluster mapping: + - test_create_map_cluster.yml: Creates a cluster with hosts and tests mapping a volume to the cluster and hosts. + - test_remove_map_cluster.yml: Removes resouces created by its cohort. + +- Playbooks for testing snapshotting: + +These two playbooks serve as a reference to the use of the modules. These exercise all modules demonstrating normal usage, idempotency and error conditions. Individual module documentation is available via `ansible-doc`. + +### Example Usage +Install the collection and cd into the collection's infi/ directory. Create an ibox yaml file in ibox_vars/. Use the example yaml file as a reference. + +The `--ask-vault-pass` options below are only required if the ibox_vars/iboxNNNN.yaml file is encrypted using ansible-vault. +``` +sudo apt install python3.8 python3.8-venv python3.8-distutils libffi-dev +python3.8 -m venv venv +source venv/bin/activate +python -m pip install -U pip +python -m pip install -r requirements.txt +cd playbooks/ +../venv/bin/ansible-playbook --extra-vars "@../ibox_vars/iboxNNNN.yaml" --ask-vault-pass test_create_resources.yml +../venv/bin/ansible-playbook --extra-vars "@../ibox_vars/iboxNNNN.yaml" --ask-vault-pass test_remove_resources.yml +deactivate +``` + +## Removal +To remove the collection, delete the collection from the path specified in the -p option during installation. + +## Copyrights and Licenses +- Copyright: (c) 2020, Infinidat <info@infinidat.com> +- GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +## Authors +The initial set of Infindat Ansible modules were written by Gregory Shulov in 2016. + +Infinidat's Professional Services (USA) team extended and improved the modules in 2019. Several modules were added. Idempotency was improved. + +## Pull requests and feature requests +Contributions will be considered via standard Git processes. If you choose to contribute, such contribution must be permanently licensed in line with the overall project license, and copyright and all other IP rights for your contribution must be permanently assigned to Infinidat and/or its successors. diff --git a/ansible_collections/infinidat/infinibox/docs/DEV_README.md b/ansible_collections/infinidat/infinibox/docs/DEV_README.md new file mode 100644 index 000000000..305395f70 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/docs/DEV_README.md @@ -0,0 +1,165 @@ +# Testing of Infinidat's Ansible Modules + +## Conventions +We use "yaml" as the extention for configuration files and "yml" for playbooks and role main.yml files. + +## Set up +- Clone ansible-infinidat-collection from one of: + - https://github.com/infinidat/ansible-infinidat-collection (external) + - https://git.infinidat.com/PSUS/ansible-infinidat-collection (internal) +- Create a Python virtualenv: + - `cd ansible-infinidat-collection` + - `python3 -m venv venv` + - `source venv/bin/activate` + - `sudo apt install libpython3.8-dev libffi-dev` + - `pip install -r requirements.txt` + +## Creating playbook extra-var files +Extra-var files define some Ansible variable necessary for running playbooks. There is an example ./ibox_vars/iboxNNNN_example.yaml. The auto_prefix value is used in the test playbooks within the names of most resources created on the Infinibox. + +Example: +``` + auto_prefix: "PSUS_ANSIBLE_" + user: "user" + password: "passwd" + system: "ibox2233" +``` + +Extra-var files containing secrets should be encrypted using ansible-vault: +- `ansible-vault [encrypt,view,edit] <extra-var file>` + +## Galaxy API +The Makefile assumes there is a file defining an API_KEY. The key may be found at https://galaxy.ansible.com/me/preferences. This file should be sourced so as to define $API_KEY. +``` +╰─➤ cat ~/.ssh/ansible-galaxy.sh +API_KEY=NNNNNNNNNNNNNN +``` + +## Creating a collection +Ansible collections require Ansible 2.9+. Complete instructions for creating and using collections is available from Ansible at https://docs.ansible.com/ansible/latest/cli/ansible-galaxy.html. + +A collection is a tarball with a specified set of files and directories that meet Ansible's collection requirements. + +## Creating resources +- `cd ./projects/playbooks` +- The ask-vault-pass option is required if the extra-var file is encrypted. +- `../venv/bin/ansible-playbook --extra-vars "@../ibox_vars/iboxNNNN.yaml" --ask-vault-pass test_create_resources.yml` + - Idempotency: Running playbooks repeatedly work correctly with all tasks showing "ok" (green). + +## Removing resources +- `cd ./projects/playbooks` +- `../venv/bin/ansible-playbook --extra-vars "@../ibox_vars/iboxNNNN.yaml" --ask-vault-pass test_remove_resources.yml` + - Running this repeatedly should work correctly with all tasks showing "ok" (green). + +## Hacking +Hacking lets one execute a module as a normal python script without Ansible. This allows use of print() and pdb for debugging. When executing modules using ansible-playbook, within a task, print statement output from the module are not displayed. + +Modules expect a JSON data file to be provided to them. This represents the equivalent JSON that Ansible would provide the module if the module is called from an Ansible task. The modules also return results to stdout in JSON form. + +### Creating hacking JSON files +Keys within JSON files must define values that match the requirements of the module to be tested. They are exactly equivalent to the fields defined in a task using the same module. + +You may find the requirements of a module using `ansible-doc`. +- Example: + - `ansible-doc infini_vol` + - See the `library` variable in the ansible.cfg file. + - `ansible-doc --module-path=~/ansible/lib/ansible/modules/storage/infinidat infini_export_client` + - This less useful example shows using the module-path option if not defined in your ansible.cfg file. In this case it is providing documentation from a github clone of the Ansible project and the older Infinidat modules Ansible comes with. + +#### Example JSON files: +- `test_logout.json`: + ``` + { + "ANSIBLE_MODULE_ARGS": { + "name": "PSUS_ANSIBLE_logout_pool", + "size": "1TB", + "vsize": "1TB", + "state": "present", + "user": "user", + "password": "passwd", + "system": "ibox1339.lab.gdc.il.infinidat.com" + } + } + ``` +- `test_export_fs.json`: + ``` + { + "ANSIBLE_MODULE_ARGS": { + "name": "/PSUS_ANSIBLE_export", + "filesystem": "PSUS_ANSIBLE_fs", + "client_list": [ + { + "client": "*", + "access": "RO", + "no_root_squash": true + } + ], + "state": "present", + "user": "user", + "password": "passwd", + "system": "ibox1339.lab.gdc.il.infinidat.com" + } + } + ``` +- `test_cluster.json`: + ``` + { + "ANSIBLE_MODULE_ARGS": { + "name": "PSUS_ANSIBLE_cluster", + "cluster_hosts": [ + { + "host_name": "PSUS_ANSIBLE_host", + "host_cluster_state": "present" + } + ], + "state": "present", + "user": "admin", + "password": "passwd", + "system": "ibox1339.lab.gdc.il.infinidat.com" + } + } + ``` + +### Executing modules without playbooks (hacking) +To run Ansible modules directly with Python and without using ansible-playbook, extra steps are required. These are documented by [Ansible module development](https://docs.ansible.com/ansible/2.9/dev_guide/developing_modules_general.html). + +Once your hacking environment is set up, you must copy ansible-infinidat-collection modules, etc. into the appropriate places within your Ansible clone. The virtualenv described above should be used. Source `hacking/env-setup` after activating the virtualenv. +``` +export ansible_clone="<path to Ansible clone>" +cd ansible-infinidat-collection/ +cp plugins/modules/infini*.py "$ansible_clone/lib/ansible/modules/storage/infinidat/" +cp plugins/module_utils/infinibox.py "$ansible_clone/lib/ansible/module_utils/" +cp plugins/doc_fragments/infinibox.py "$ansible_clone/lib/ansible/plugins/doc_fragments/" +``` + +`bin/install_modules_for_hacking.sh` may be used to copy the files described above. If executed from anywhere with in the ansible-infinidat-collection working copy, it will find the proper files and copy them into the specified Ansible source clone. The existing files in the clone will be overwritten. +``` +./bin/install_modules_for_hacking.sh <path to clone of Ansible's src> +``` + +Run/hack a module: +``` +export test_jsons="<path to test JSON files>" +python -m ansible.modules.storage.infinidat.infini_host "$test_jsons/test_host.json" +python -m ansible.modules.storage.infinidat.infini_host "$test_jsons/test_host.json" 2>&1 | grep -v Insecure +python -m ansible.modules.storage.infinidat.infini_host "$test_jsons/test_host.json" 2>&1 | grep -v Insecure | jq --sort-keys '.' +``` + +### Errors and Workarounds +- `Command "python setup.py egg_info" failed with error code 1 in /tmp/..../` + - `(venv) $ python3 -m pip install -U pip` + - `(venv) $ python3 -m pip install -U setuptools` + +### Set colors for those who are color challenged (optional) +Use of jq and pygmentize is not required, but we've found it useful. Use pygmentize to colorize JSON data using the autumn theme. Pymentize may be installed via pip. + +Use jq to pretty print JSON. See https://stedolan.github.io/jq/ +- -c: Optionally, use compact output. This displays JSON in a much shorter form, but may be harder to read. +- --sort-keys: Sort keys. +- The period is the simplest jq filter. It is a null filter showing all input. + +``` +pyg_style="autumn" +jqpyg="pygmentize -O style=$pyg_style -l json" +python -m ansible.modules.storage.infinidat.infini_port test_ports_port.json 2>&1 | grep -v Insecure | jq --sort-keys -c . | eval $jqpyg +``` diff --git a/ansible_collections/infinidat/infinibox/ibox_vars/iboxCICD.yaml b/ansible_collections/infinidat/infinibox/ibox_vars/iboxCICD.yaml new file mode 100644 index 000000000..476b19b8b --- /dev/null +++ b/ansible_collections/infinidat/infinibox/ibox_vars/iboxCICD.yaml @@ -0,0 +1,10 @@ +$ANSIBLE_VAULT;1.1;AES256 +66343034363232313933643233373938303539343932613065656639303736666261396638333565 +6430326563653366353435663339616638396164316633370a303964386364356365663064613766 +36616565626561396434303535663133656562646632383139393866393334383331623133393030 +3838663637366337310a333462633161316239663964653835336534636662393730313731666433 +66646237393738323330383465396437666365626636316162373964653737383034353530306633 +33643337373164376664643465646437316530623363643634323835303030333935346637613236 +61666331366661336234666436656665663464353664363761393866653263356434313232363564 +65346630386262633962386537376234646666326161343738303962306537323162306362636634 +66643231636466646539386137363037346434363962653834353139386434643464 diff --git a/ansible_collections/infinidat/infinibox/ibox_vars/iboxNNNN_example.yaml b/ansible_collections/infinidat/infinibox/ibox_vars/iboxNNNN_example.yaml new file mode 100644 index 000000000..f802b163b --- /dev/null +++ b/ansible_collections/infinidat/infinibox/ibox_vars/iboxNNNN_example.yaml @@ -0,0 +1,12 @@ +# This an example file for setting variables for playbooks like test_create_resources.yml. +# +# It is recommended that these files be encrypted: +# - $ ansible-vault encrypt <file> +# +# Any value for auto_prefix may be used. auto_prefix is used in every resource created by +# the example playbooks, making resources easy to find. + +auto_prefix: "PSUS_ANSIBLE_" +user: "user" +password: "password" +system: "iboxNNNN" diff --git a/ansible_collections/infinidat/infinibox/meta/execution-environment.yml b/ansible_collections/infinidat/infinibox/meta/execution-environment.yml new file mode 100644 index 000000000..8a8bdd1eb --- /dev/null +++ b/ansible_collections/infinidat/infinibox/meta/execution-environment.yml @@ -0,0 +1,8 @@ +version: 1 + +build_arg_defaults: + EE_BASE_IMAGE: "registry.redhat.io/ansible-automation-platform-21/ee-minimal-rhel8:latest" +ansible_config: "ansible.cfg" + +dependencies: + python: requirements.txt diff --git a/ansible_collections/infinidat/infinibox/meta/runtime.yml b/ansible_collections/infinidat/infinibox/meta/runtime.yml new file mode 100644 index 000000000..112c4e065 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/meta/runtime.yml @@ -0,0 +1 @@ +requires_ansible: ">=2.9.10" diff --git a/ansible_collections/infinidat/infinibox/playbooks/ansible.cfg b/ansible_collections/infinidat/infinibox/playbooks/ansible.cfg new file mode 100644 index 000000000..2024423d0 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/ansible.cfg @@ -0,0 +1,6 @@ +[defaults] +doc_fragment_plugins = ../doc_fragments +filter_plugins = ../plugins/filters +library = ../plugins/modules +module_utils = ../plugins/module_utils +roles_path = ../roles diff --git a/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_runtest.yml b/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_runtest.yml new file mode 100644 index 000000000..54978a53e --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_runtest.yml @@ -0,0 +1,122 @@ +--- +### Localhost +- hosts: forensics + gather_facts: false + collections: + - infinidat.infinibox + vars: + network_space: InfiniSafe-Fenced-Network # iSCSI + service: ISCSI_SERVICE + pool: infinisafe + volume: app_vol + snap: app_snap + host: forensic-validation-host + host_iqn: iqn.1993-08.org.debian:01:62ebda3b76cc # io-wt-35 + ibox_portal: 172.31.32.145 + ibox: ibox1521 + ibox_iqn: iqn.2009-11.com.infinidat:storage:infinibox-sn-1521 + tasks: + + - name: Create {{ service }} network space named {{ network_space }} + infini_network_space: + name: "{{ network_space }}" + state: present + service: "{{ service }}" + interfaces: + - 1680 + - 1679 + - 1678 + netmask: 19 + network: 172.31.32.0 + default_gateway: 172.31.63.254 + # rate_limit: 8 + # mtu: 1280 + ips: + - 172.31.32.145 + - 172.31.32.146 + - 172.31.32.147 + - 172.31.32.148 + - 172.31.32.149 + - 172.31.32.150 + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Create forensic host {{ host }} + infini_host: + name: "{{ host }}" + state: present + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Map snapshot {{ snap }} to host {{ host }} + infini_map: + host: "{{ host }}" + volume: "{{ snap }}" + state: present + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Add port to host {{ host }} + infini_port: + host: "{{ host }}" + iqns: "{{ host_iqn }}" + state: present + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + ### Forensics Host + - name: Connect forensics host {{ host }} to Infinibox {{ ibox }} + ansible.builtin.shell: | + iscsiadm --mode discoverydb --type sendtargets --portal {{ ibox_portal }} --discover + iscsiadm --mode node --targetname={{ ibox_iqn }} --op update --name=node.session.auth.username --value={{ user }} + iscsiadm --mode discovery --type sendtargets --portal {{ ibox_portal }} --op show + iscsiadm --mode node --targetname {{ ibox_iqn }} --portal {{ ibox_portal }} --login + rescan-scsi-bus.sh + changed_when: false + become: true + + # Run forensic tests on snapshot {{ snap }} + - name: Forensically test snapshot {{ snap }} is clean using host {{ host }} + ansible.builtin.shell: | + true + changed_when: false + register: is_snapshot_clean + + ### Localhost + - name: debug + ansible.builtin.debug: + msg: Snapshot {{ snap }} PASSED testing + when: is_snapshot_clean.rc == 0 + delegate_to: localhost + + - name: debug + ansible.builtin.debug: + msg: Snapshot {{ snap }} FAILED testing. Do not use this snapshot. + when: is_snapshot_clean.rc != 0 + delegate_to: localhost + + - name: Restoring volume {{ volume }} from known clean snapshot {{ snap }} + infini_vol: + name: "{{ snap }}" + state: present + parent_volume_name: "{{ volume }}" + volume_type: snapshot + restore_volume_from_snapshot: true + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + when: is_snapshot_clean.rc == 0 + delegate_to: localhost diff --git a/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_setup.yml b/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_setup.yml new file mode 100644 index 000000000..5d58b9741 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_setup.yml @@ -0,0 +1,50 @@ +--- +- hosts: localhost + gather_facts: true # Required for ansible_date_time + collections: + - infinidat.infinibox + vars: + network_space: InfiniSafe-Fenced-Network # iSCSI + service: ISCSI_SERVICE + pool: infinisafe + volume: app_vol + snap: app_snap + host: forensic-validation-host + host_iqn: iqn.1993-08.org.debian:01:62ebda3b76cc # io-wt-35 + tasks: + + - name: Create pool {{ pool }} + infini_pool: + name: "{{ pool }}" + size: 1TB + vsize: 1TB + state: present + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: Create volume {{ volume }} under pool {{ pool }} + infini_vol: + name: "{{ volume }}" + size: 1GB + pool: "{{ pool }}" + state: present + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: Create and lock (1 minute) snapshot {{ snap }} from volume {{ volume }} + infini_vol: + name: "{{ snap }}" + state: present + volume_type: snapshot + parent_volume_name: "{{ volume }}" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(minutes=1) }}" + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" diff --git a/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_teardown.yml b/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_teardown.yml new file mode 100644 index 000000000..6213f6c08 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/infinisafe_demo_teardown.yml @@ -0,0 +1,105 @@ +--- +### Localhost +- hosts: forensics + gather_facts: false + collections: + - infinidat.infinibox + vars: + network_space: InfiniSafe-Fenced-Network # iSCSI + service: ISCSI_SERVICE + pool: infinisafe + volume: app_vol + snap: app_snap + host: forensic-validation-host + host_iqn: iqn.1993-08.org.debian:01:62ebda3b76cc # io-wt-35 + ibox_portal: 172.31.32.145 + ibox: ibox1521 + ibox_iqn: iqn.2009-11.com.infinidat:storage:infinibox-sn-1521 + ibox_portals: 172.31.32.148 172.31.32.146 172.31.32.149 172.31.32.145 172.31.32.150 172.31.32.147 + tasks: + + - name: Unmap snapshot {{ snap }} from host {{ host }} + infini_map: + host: "{{ host }}" + volume: "{{ snap }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Remove port from host {{ host }} + infini_port: + host: "{{ host }}" + iqns: "{{ host_iqn }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + +### Forensics Host + - name: Disconnect forensics host {{ host }} from Infinibox {{ ibox }} + ansible.builtin.shell: | + for i in {{ ibox_portals }}; do + iscsiadm --mode node --target {{ ibox_iqn }} -p $i --logout + done + for i in {{ ibox_portals }}; do + iscsiadm --mode discoverydb -t sendtargets -p $i -o delete --discover + done + changed_when: true + become: true + +### Localhost + - name: Remove network space named {{ network_space }} + infini_network_space: + name: "{{ network_space }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Remove snapshot {{ snap }} created from volume {{ volume }} + infini_vol: + name: "{{ snap }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Remove volume {{ volume }} under pool {{ pool }} + infini_vol: + name: "{{ volume }}" + pool: "{{ pool }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Remove pool {{ pool }} + infini_pool: + name: "{{ pool }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost + + - name: Remove forensic host {{ host }} + infini_host: + name: "{{ host }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + delegate_to: localhost diff --git a/ansible_collections/infinidat/infinibox/playbooks/inventory b/ansible_collections/infinidat/infinibox/playbooks/inventory new file mode 100644 index 000000000..15954ef41 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/inventory @@ -0,0 +1,2 @@ +[forensics] +io-wt-35.lab.wt.us.infinidat.com ansible_python_interpreter=python3.8 diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_create_map_cluster.yml b/ansible_collections/infinidat/infinibox/playbooks/test_create_map_cluster.yml new file mode 100644 index 000000000..cf807fcbb --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_create_map_cluster.yml @@ -0,0 +1,295 @@ +--- +- hosts: localhost + gather_facts: false + collections: + - infinidat.infinibox + tasks: + + - name: NEGATIVE test -> Map volume {{ auto_prefix }}vol specifying both a cluster and a host + infini_map: + host: "{{ auto_prefix }}host1" + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: + - '"both to be provided" not in result.msg' + - not result.failed + + - name: NEGATIVE test -> Unmap volume {{ auto_prefix }}vol specifying both a cluster and a host + infini_map: + host: "{{ auto_prefix }}host1" + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: + - '"both to be provided" not in result.msg' + - not result.failed + + - name: NEGATIVE test -> Stat volume {{ auto_prefix }}vol specifying both a cluster and a host + infini_map: + host: "{{ auto_prefix }}host1" + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: + - '"both to be provided" not in result.msg' + - not result.failed + + - name: POSITIVE test -> Create pool {{ auto_prefix }}pool + infini_pool: + name: "{{ auto_prefix }}pool" + size: 1TB + vsize: 1TB + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create thin volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create host {{ auto_prefix }}host1 for cluster mapping + infini_host: + name: "{{ auto_prefix }}host1" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create host {{ auto_prefix }}host2 for cluster mapping + infini_host: + name: "{{ auto_prefix }}host2" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create host {{ auto_prefix }}host3 for host mapping + infini_host: + name: "{{ auto_prefix }}host3" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create cluster {{ auto_prefix }}cluster with hosts 1 and 2 for cluster mapping + infini_cluster: + name: "{{ auto_prefix }}cluster" + cluster_hosts: + - host_name: "{{ auto_prefix }}host1" + host_cluster_state: present + - host_name: "{{ auto_prefix }}host2" + host_cluster_state: present + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Map volume {{ auto_prefix }}vol to cluster {{ auto_prefix }}cluster + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Map volume {{ auto_prefix }}vol to cluster {{ auto_prefix }}cluster again + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: + - '"already exists using" not in result.msg' + - result.changed + + - name: POSITIVE test -> Stat map of volume {{ auto_prefix }}vol to cluster {{ auto_prefix }}cluster + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: cluster_stat + + - name: POSITIVE test -> Show map stat + ansible.builtin.debug: + msg: "Map stat: {{ cluster_stat }}" + + - name: POSITIVE test -> Map volume {{ auto_prefix }}vol to host {{ auto_prefix }}host3 + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Map volume {{ auto_prefix }}vol to host {{ auto_prefix }}host3 again + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: + - '"already exists using" not in result.msg' + - result.changed + + - name: POSITIVE test -> Stat map of volume {{ auto_prefix }}vol to host {{ auto_prefix }}host3 + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: host_stat + + - name: POSITIVE test -> Show map stat + ansible.builtin.debug: + msg: "Map stat: {{ host_stat }}" + + # Since the host is in the cluster and the volume is already mapped to the cluster, mapping the volume to the host becomes a NOOP. + - name: IDEMPOTENT test -> Map volume {{ auto_prefix }}vol to host {{ auto_prefix }}host1 which is also in {{ auto_prefix }}cluster + infini_map: + host: "{{ auto_prefix }}host1" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: + - '"already exists using" not in result.msg' + - result.changed + +### Test mapping of volume to a host using specified lun. + - name: NEGATIVE test -> Map volume {{ auto_prefix }}vol to host {{ auto_prefix }}host3 again using lun 99 when already mapped + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + lun: 99 + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: new_lun_fail + failed_when: + - '"Cannot change the lun" not in new_lun_fail.msg' + - result.changed + + - name: POSITIVE test -> Unmap volume {{ auto_prefix }}vol from host {{ auto_prefix }}host3 + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Map volume {{ auto_prefix }}vol to host {{ auto_prefix }}host3 using lun 99 when not already mapped + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + lun: 99 + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat map of volume {{ auto_prefix }}vol to host {{ auto_prefix }}host3 to check lun 99 used + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: new_lun_success + failed_when: + - '"using lun 99" not in new_lun_success.msg' + - new_lun_success.volume_lun != 99 + + - name: POSITIVE test -> Show lun mapping message + ansible.builtin.debug: + msg: "Changed lun mapping message: {{ new_lun_success.msg }}" +### End test mapping of volume to a host using specified lun. + +### Test mapping of volume to a cluster using specified lun. + - name: NEGATIVE test -> Map volume {{ auto_prefix }}vol to cluster {{ auto_prefix }}cluster again using lun 98 when already mapped + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + lun: 98 + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: new_lun_fail + failed_when: + - '"Cannot change the lun" not in new_lun_fail.msg' + - result.changed + + - name: POSITIVE test -> Unmap volume {{ auto_prefix }}vol from cluster {{ auto_prefix }}cluster + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Map volume {{ auto_prefix }}vol to cluster {{ auto_prefix }}cluster using lun 98 when not already mapped + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + lun: 98 + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat map of volume {{ auto_prefix }}vol to cluster {{ auto_prefix }}cluster to check lun 98 used + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: new_lun_success + failed_when: + - '"using lun 98" not in new_lun_success.msg' + - new_lun_success.volume_lun != 98 + + - name: POSITIVE test -> Show lun mapping message + ansible.builtin.debug: + msg: "Changed lun mapping message: {{ new_lun_success.msg }}" + ### End test mapping of volume to a cluster using specified lun. diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_create_network_spaces.yml b/ansible_collections/infinidat/infinibox/playbooks/test_create_network_spaces.yml new file mode 100644 index 000000000..b8bced550 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_create_network_spaces.yml @@ -0,0 +1,47 @@ +--- +- hosts: localhost + gather_facts: false + collections: + - infinidat.infinibox + vars: + name: iSCSI + service: ISCSI_SERVICE + tasks: + + - name: POSITIVE test -> Create {{ service }} network space named {{ name }} + infini_network_space: + name: "{{ name }}" + state: present + interfaces: + - 1680 + - 1679 + - 1678 + service: "{{ service }}" + netmask: 19 + network: 172.31.32.0 + default_gateway: 172.31.63.254 + # rate_limit: 8 + # mtu: 1280 + ips: + - 172.31.32.145 + - 172.31.32.146 + - 172.31.32.147 + - 172.31.32.148 + - 172.31.32.149 + - 172.31.32.150 + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: create_out + + - name: debug + ansible.builtin.debug: + var: create_out + + - name: POSITIVE test -> Stat {{ service }} network space named {{ name }} + infini_network_space: + name: "{{ name }}" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_create_resources.yml b/ansible_collections/infinidat/infinibox/playbooks/test_create_resources.yml new file mode 100644 index 000000000..3ca9b5542 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_create_resources.yml @@ -0,0 +1,631 @@ +--- +- hosts: localhost + gather_facts: true # Required for ansible_date_time + collections: + - infinidat.infinibox + tasks: + + - name: NEGATIVE test -> Create file system named {{ auto_prefix }}fs under a pool that does not exist + infini_fs: + name: "{{ auto_prefix }}fs" + size: 1GB + pool: "{{ auto_prefix }}pool_missing" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "'pool_missing' not in result.msg" + when: not ansible_check_mode + + - name: POSITIVE test -> Create pool {{ auto_prefix }}pool + infini_pool: + name: "{{ auto_prefix }}pool" + size: 1TB + vsize: 1TB + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat pool {{ auto_prefix }}pool + infini_pool: + name: "{{ auto_prefix }}pool" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create default THIN, file system named {{ auto_prefix }}fs_default under pool {{ auto_prefix }}pool + # See IBox settings: Dataset default provisioning. + infini_fs: + name: "{{ auto_prefix }}fs_default" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat file system named {{ auto_prefix }}fs_default under pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs_default" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: def_stat + + - debug: + msg: stat - {{ def_stat }} + + - name: POSITIVE test -> Create THICK file system named {{ auto_prefix }}fs_thick under pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs_thick" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + thin_provision: false + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create THIN file system named {{ auto_prefix }}fs under pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + thin_provision: true + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Change THIN file system named {{ auto_prefix }}fs to THICK provisioning + infini_fs: + name: "{{ auto_prefix }}fs" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + thin_provision: false + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Change THICK file system named {{ auto_prefix }}fs back to THIN provisioning + infini_fs: + name: "{{ auto_prefix }}fs" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + thin_provision: true + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat file system named {{ auto_prefix }}fs under pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs" + pool: "{{ auto_prefix }}pool" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Export file system {{ auto_prefix }}fs + infini_export: + name: "/{{ auto_prefix }}export" + filesystem: "{{ auto_prefix }}fs" + client_list: + - client: "*" + access: "RO" + no_root_squash: true + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat file system export {{ auto_prefix }}export + infini_export: + name: "/{{ auto_prefix }}export" + filesystem: "{{ auto_prefix }}fs" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: NEGATIVE test -> Export file system {{ auto_prefix }}fs that does not exist + infini_export: + name: "/{{ auto_prefix }}export_missing" + filesystem: "{{ auto_prefix }}fs_missing" + client_list: + - client: "*" + access: "RO" + no_root_squash: true + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "not result.msg | regex_search('File system.*not found')" + when: not ansible_check_mode + + - name: POSITIVE test -> Create export client for export /{{ auto_prefix }}export + infini_export_client: + export: "/{{ auto_prefix }}export" + client: "20.20.20.20" + state: present + access_mode: "RO" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + # TODO - stat export client + + - name: NEGATIVE test -> Create export client for export that does not exist + infini_export_client: + export: "/{{ auto_prefix }}export_missing" + client: 20.20.20.20 + state: present + access_mode: "RO" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "not result.msg | regex_search('Export.*not found')" + when: not ansible_check_mode + + - name: NEGATIVE test -> Create volume {{ auto_prefix }}vol_in_pool_missing under pool that does not exist + infini_vol: + name: "{{ auto_prefix }}vol_in_pool_missing" + size: 1GB + pool: "{{ auto_prefix }}pool_missing" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "'Pool not found' not in result.msg" + # failed_when: "'pool_missing' not in result.msg" + when: not ansible_check_mode + + - name: POSITIVE test -> Create thin volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create thick volume {{ auto_prefix }}vol_thick under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol_thick" + size: 1GB + pool: "{{ auto_prefix }}pool" + thin_provision: false + write_protected: true + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool + register: output + infini_vol: + name: "{{ auto_prefix }}vol" + pool: "{{ auto_prefix }}pool" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat vol serial number + infini_vol: + state: stat + serial: "{{ output.serial }}" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create snapshot {{ auto_prefix }}vol_snap from volume {{ auto_prefix }}vol + infini_vol: + name: "{{ auto_prefix }}vol_snap" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: DEBUG test -> Find the current date-time (WARNING - Time marks when the playbook gathered facts) + ansible.builtin.debug: + var=ansible_date_time.iso8601_micro + + # Note: For collection filters, Ansible does not honor the + # collections list at the top of this file. + # One must use a FQCN for filters such as + # infinidat.infinibox.delta_time. + - name: POSITIVE test -> Create and lock for 2 minutes snapshot {{ auto_prefix }}vol_snap_locked from volume {{ auto_prefix }}vol + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(minutes=2) }}" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" + + - name: POSITIVE test -> Extend lock to 3 minutes for {{ auto_prefix }}vol_snap_locked without refresh + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(minutes=3) }}" + snapshot_lock_only: true + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" + + - name: NEGATIVE test -> Attempt to extend lock without refresh on a snapshot that does not exist. + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked_missing" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(minutes=3) }}" + snapshot_lock_only: true + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "not result.msg | regex_search('Snapshot does not exist. Cannot comply')" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" + + - name: NEGATIVE test -> Attempt to create snapshot locked for 31 days, 31 days exceeds 30 day maximum lock time enforced by infini_vol module (not api) + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked_too_long" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(days=31) }}" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "not result.msg | regex_search('snapshot_lock_expires_at exceeds.*days in the future')" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" + + - name: NEGATIVE test -> Attempt to remove locked snapshot {{ auto_prefix }}vol_snap_locked + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "'Cannot delete snapshot. Locked' not in result.msg" + + - name: POSITIVE test -> Wait for lock on {{ auto_prefix }}vol_snap_locked to expire + ansible.builtin.pause: + seconds: 181 + prompt: Waiting for {{ auto_prefix }}vol_snap_locked to expire + + - name: POSITIVE test -> Remove snapshot {{ auto_prefix }}vol_snap_locked with expired lock + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create host {{ auto_prefix }}host + infini_host: + name: "{{ auto_prefix }}host" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + # Second host used for testing infini_cluster + - name: POSITIVE test -> Create host {{ auto_prefix }}host2 + infini_host: + name: "{{ auto_prefix }}host2" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat host {{ auto_prefix }}host + infini_host: + name: "{{ auto_prefix }}host" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Add one wwns port to {{ auto_prefix }}host + infini_port: + host: PSUS_ANSIBLE_host + state: present + wwns: + - "21:00:00:24:ff:78:69:e4" + # iqns: [] + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Add a second wwn port plus two iscsi ports to {{ auto_prefix }}host + infini_port: + host: PSUS_ANSIBLE_host + state: present + wwns: + - "21:00:00:24:ff:78:69:e5" + iqns: + - "iqn.1998-01.com.vmware:5d2f90f6-1987-c06c-4d2f-246e9602d5e0-aaaaaaaa" + - "iqn.1998-01.com.vmware:5d2f90f6-1987-c06c-4d2f-246e9602d5e0-bbbbbbbb" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat ports on {{ auto_prefix }}host + infini_port: + host: PSUS_ANSIBLE_host + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat host {{ auto_prefix }}host after ports added + infini_host: + name: "{{ auto_prefix }}host" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: NEGATIVE test -> Map volume {{ auto_prefix }}vol to host that does not exist + infini_map: + host: "{{ auto_prefix }}host_missing" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "not result.msg | regex_search('Neither host.*nor cluster.*found')" + when: not ansible_check_mode + + - name: POSITIVE test -> Map volume {{ auto_prefix }}vol to host {{ auto_prefix }}host + infini_map: + host: "{{ auto_prefix }}host" + volume: "{{ auto_prefix }}vol" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Rescan after mapping + shell: | + rescan-scsi-bus.sh + become: True + register: rescan + failed_when: "rescan.rc != 0 and 'not found' not in rescan.stderr" + + - name: POSITIVE test -> Stat map of volume {{ auto_prefix }}vol to host {{ auto_prefix }}host + infini_map: + host: "{{ auto_prefix }}host" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove mapping of volume {{ auto_prefix }}vol from host {{ auto_prefix }}host + infini_map: + host: "{{ auto_prefix }}host" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Rescan with remove option after removing mapping + shell: | + rescan-scsi-bus.sh --remove + become: True + register: rescan + failed_when: "rescan.rc != 0 and 'not found' not in rescan.stderr" + + - name: POSITIVE test -> Map volume {{ auto_prefix }}vol to host {{ auto_prefix }}host using lun 0 + infini_map: + host: "{{ auto_prefix }}host" + volume: "{{ auto_prefix }}vol" + lun: 0 + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Rescan after mapping + shell: | + rescan-scsi-bus.sh + become: True + register: rescan + failed_when: "rescan.rc != 0 and 'not found' not in rescan.stderr" + + - name: POSITIVE test -> Stat map of volume {{ auto_prefix }}vol to host {{ auto_prefix }}host using lun 0 + infini_map: + host: "{{ auto_prefix }}host" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: check_lun + tags: + - dev + + - name: ASSERT test -> Check lun 0 set + ansible.builtin.assert: + that: + - check_lun.volume_lun == 0 + tags: + - dev + + - name: POSITIVE test -> Create user {{ auto_prefix }}pool_admin_user with pool_admin role managing pool {{ auto_prefix }}pool + infini_user: + user_name: "{{ auto_prefix }}pool_admin_user" + user_email: "{{ auto_prefix }}pool_admin_user@example.com" + user_password: "secret1" + user_role: "pool_admin" + user_enabled: "true" + user_pool: "{{ auto_prefix }}pool" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Disable user {{ auto_prefix }}pool_admin_user + infini_user: + user_name: "{{ auto_prefix }}pool_admin_user" + user_email: "{{ auto_prefix }}pool_admin_user@example.com" + user_password: "secret1" + user_role: "pool_admin" + user_enabled: "false" + user_pool: "{{ auto_prefix }}pool" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Stat user {{ auto_prefix }}pool_admin_user + infini_user: + user_name: "{{ auto_prefix }}pool_admin_user" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Reset password for user {{ auto_prefix }}pool_admin_user + infini_user: + user_name: "{{ auto_prefix }}pool_admin_user" + user_password: "secret_new" + state: reset_password + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create user {{ auto_prefix }}admin_user with admin role + infini_user: + user_name: "{{ auto_prefix }}admin_user" + user_email: "{{ auto_prefix }}admin_user@example.com" + user_password: "secret2" + user_role: "admin" + user_enabled: "true" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create user {{ auto_prefix }}read_only_user with read_only role + infini_user: + user_name: "{{ auto_prefix }}read_only_user" + user_email: "{{ auto_prefix }}read_only_user@example.com" + user_password: "secret3" + user_role: "read_only" + user_enabled: "true" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create cluster {{ auto_prefix }}cluster with two hosts + infini_cluster: + name: "{{ auto_prefix }}cluster" + cluster_hosts: + - host_name: "{{ auto_prefix }}host" + host_cluster_state: present + - host_name: "{{ auto_prefix }}host2" + host_cluster_state: present + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove {{ auto_prefix }}host from cluster {{ auto_prefix }}cluster. Leave {{ auto_prefix }}host2. + infini_cluster: + name: "{{ auto_prefix }}cluster" + cluster_hosts: + - host_name: "{{ auto_prefix }}host" + host_cluster_state: absent + - host_name: "{{ auto_prefix }}host2" + host_cluster_state: present + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Re-add {{ auto_prefix }}host to cluster {{ auto_prefix }}cluster. Remove {{ auto_prefix }}host2. + infini_cluster: + name: "{{ auto_prefix }}cluster" + cluster_hosts: + - host_name: "{{ auto_prefix }}host" + host_cluster_state: present + - host_name: "{{ auto_prefix }}host2" + host_cluster_state: absent + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Re-add {{ auto_prefix }}host to cluster {{ auto_prefix }}cluster again. Remove {{ auto_prefix }}host2 again. + infini_cluster: + name: "{{ auto_prefix }}cluster" + cluster_hosts: + - host_name: "{{ auto_prefix }}host" + host_cluster_state: present + - host_name: "{{ auto_prefix }}host2" + host_cluster_state: absent + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: NEGATIVE test -> Attempt to add {{ auto_prefix }}host to cluster {{ auto_prefix }}cluster with missing host_cluster_state key:value + infini_cluster: + name: "{{ auto_prefix }}cluster" + cluster_hosts: + - host_name: "{{ auto_prefix }}host" + # host_cluster_state: present + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "'require host_name and host_cluster_state' not in result.msg" + + - name: NEGATIVE test -> Attempt to add {{ auto_prefix }}host to cluster {{ auto_prefix }}cluster with an unsupported key:value + infini_cluster: + name: "{{ auto_prefix }}cluster" + cluster_hosts: + - host_name: "{{ auto_prefix }}host" + host_cluster_state: present + host_unknown_key: unknown_value + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "'require host_name and host_cluster_state' not in result.msg" diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_create_snapshots.yml b/ansible_collections/infinidat/infinibox/playbooks/test_create_snapshots.yml new file mode 100644 index 000000000..bb4db264e --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_create_snapshots.yml @@ -0,0 +1,109 @@ +--- +- hosts: localhost + gather_facts: true # Required for ansible_date_time + collections: + - infinidat.infinibox + tasks: + + - name: POSITIVE test -> Create pool {{ auto_prefix }}pool + infini_pool: + name: "{{ auto_prefix }}pool" + size: 1TB + vsize: 1TB + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create thin volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: present + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Create snapshot {{ auto_prefix }}vol_snap from volume {{ auto_prefix }}vol + infini_vol: + name: "{{ auto_prefix }}vol_snap" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: DEBUG test -> Find the current date-time (WARNING - Time marks when the playbook gathered facts) + ansible.builtin.debug: + var=ansible_date_time.iso8601_micro + + # Note: For collection filters, Ansible does not honor the + # collections list at the top of this file. + # One must use a FQCN for filters such as + # infinidat.infinibox.delta_time. + - name: POSITIVE test -> Create and lock for 2 minutes snapshot {{ auto_prefix }}vol_snap_locked from volume {{ auto_prefix }}vol + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(minutes=2) }}" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" + + - name: POSITIVE test -> Extend lock to 3 minutes for {{ auto_prefix }}vol_snap_locked without refresh + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(minutes=3) }}" + snapshot_lock_only: true + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" + + - name: NEGATIVE test -> Attempt to create snapshot locked for 31 days, 31 days exceeds 30 day maximum lock time enforced by infini_vol module (not API) + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked_too_long" + state: present + volume_type: snapshot + parent_volume_name: "{{ auto_prefix }}vol" + snapshot_lock_expires_at: "{{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(days=31) }}" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "not result.msg | regex_search('snapshot_lock_expires_at exceeds.*days in the future')" + vars: + fmt: "%Y-%m-%dT%H:%M:%S.%fZ" + + - name: NEGATIVE test -> Attempt to remove locked snapshot {{ auto_prefix }}vol_snap_locked + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: "'Cannot delete snapshot. Locked' not in result.msg" + + - name: POSITIVE test -> Wait for lock on {{ auto_prefix }}vol_snap_locked to expire + ansible.builtin.pause: + seconds: 181 + prompt: Waiting for {{ auto_prefix }}vol_snap_locked to expire + + - name: POSITIVE test -> Lock expired. Remove snapshot {{ auto_prefix }}vol_snap_locked. + infini_vol: + name: "{{ auto_prefix }}vol_snap_locked" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_remove_map_cluster.yml b/ansible_collections/infinidat/infinibox/playbooks/test_remove_map_cluster.yml new file mode 100644 index 000000000..8aaa765fb --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_remove_map_cluster.yml @@ -0,0 +1,183 @@ +--- +- hosts: localhost + gather_facts: false + collections: + - infinidat.infinibox + tasks: + + - name: POSITIVE test -> Stat mapping of volume {{ auto_prefix }}vol to host {{ auto_prefix }}host1 + infini_map: + host: "{{ auto_prefix }}host1" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: host_stat + failed_when: + - '"vol is mapped to host" not in host_stat.msg' + - '"host1" not in host_stat.msg' + - host_stat.failed + + - name: POSITIVE test -> Show map stat + ansible.builtin.debug: + msg: "Map stat: {{ host_stat }}" + + - name: POSITIVE test -> Stat mapping of volume {{ auto_prefix }}vol to cluster {{ auto_prefix }}cluster + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: cluster_stat + failed_when: + - '"vol is mapped to cluster" not in cluster_stat.msg' + - cluster_stat.failed + + - name: POSITIVE test -> Show map stat + ansible.builtin.debug: + msg: "Map stat: {{ cluster_stat }}" + + # WARNING: Assume we have a vol mapped to a cluster with hosts host1 and host2. + # Then we unmap the vol from "host1" as shown below. + - name: POSITIVE test -> Remove mapping of volume {{ auto_prefix }}vol from host {{ auto_prefix }}host1 + infini_map: + host: "{{ auto_prefix }}host1" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + # This will UNMAP the vol from the entire CLUSTER! + - name: NEGATIVE test -> Stat removed mapping of volume {{ auto_prefix }}vol from host {{ auto_prefix }}host1 + infini_map: + host: "{{ auto_prefix }}host1" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: host_stat + failed_when: + - '"mapped to neither" in host_stat.msg' + - not host_stat.failed + + - name: POSITIVE test -> Show map stat + ansible.builtin.debug: + msg: "Map stat: {{ host_stat }}" + + - name: NEGATIVE test -> Stat removed mapping of volume {{ auto_prefix }}vol from cluster {{ auto_prefix }}cluster + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: stat + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: cluster_stat + failed_when: + - '"mapped to neither host nor cluster" in cluster_stat.msg' + - not cluster_stat.failed + + - name: POSITIVE test -> Show map stat + ansible.builtin.debug: + msg: "Map stat: {{ cluster_stat }}" + + - name: POSITIVE test -> Remove mapping of volume {{ auto_prefix }}vol from host {{ auto_prefix }}host3 + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove mapping of volume {{ auto_prefix }}vol from host {{ auto_prefix }}host3 again + infini_map: + host: "{{ auto_prefix }}host3" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + register: result + failed_when: + - '"was not mapped" not in result.msg' + - result.changed + + - name: POSITIVE test -> Show map stat + ansible.builtin.debug: + msg: "result: {{ result.msg }}" + + - name: POSITIVE test -> Remove mapping of volume {{ auto_prefix }}vol from cluster {{ auto_prefix }}cluster + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove mapping of volume {{ auto_prefix }}vol from cluster {{ auto_prefix }}cluster + infini_map: + cluster: "{{ auto_prefix }}cluster" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + failed_when: + - '"was not mapped" not in result.msg' + - result.changed + + - name: POSITIVE test -> Remove cluster {{ auto_prefix }}cluster + infini_cluster: + name: "{{ auto_prefix }}cluster" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove host {{ auto_prefix }}host1 + infini_host: + name: "{{ auto_prefix }}host1" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove host {{ auto_prefix }}host2 + infini_host: + name: "{{ auto_prefix }}host2" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove host {{ auto_prefix }}host3 + infini_host: + name: "{{ auto_prefix }}host3" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove thin volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol" + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove pool {{ auto_prefix }}pool + infini_pool: + name: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_remove_network_spaces.yml b/ansible_collections/infinidat/infinibox/playbooks/test_remove_network_spaces.yml new file mode 100644 index 000000000..3532008e9 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_remove_network_spaces.yml @@ -0,0 +1,18 @@ +--- +- hosts: localhost + gather_facts: false + collections: + - infinidat.infinibox + vars: + name: iSCSI + service: iSCSI + tasks: + + - name: POSITIVE test -> Remove network space named {{ name }} + infini_network_space: + name: "{{ name }}" + state: absent + + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_remove_resources.yml b/ansible_collections/infinidat/infinibox/playbooks/test_remove_resources.yml new file mode 100644 index 000000000..c7cb121df --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_remove_resources.yml @@ -0,0 +1,234 @@ +--- +- hosts: localhost + gather_facts: false + collections: + - infinidat.infinibox + tasks: + + - name: POSITIVE test -> Remove cluster {{ auto_prefix }}cluster + infini_cluster: + name: "{{ auto_prefix }}cluster" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove cluster {{ auto_prefix }}cluster again + infini_cluster: + name: "{{ auto_prefix }}cluster" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove mapping of volume {{ auto_prefix }}vol from host {{ auto_prefix }}host + infini_map: + host: "{{ auto_prefix }}host" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Rescan with remove option after removing mapping + shell: | + rescan-scsi-bus.sh --remove + become: True + register: rescan + failed_when: "rescan.rc != 0 and 'not found' not in rescan.stderr" + + - name: IDEMPOTENT test -> Remove mapping of volume {{ auto_prefix }}vol from host {{ auto_prefix }}host again + infini_map: + host: "{{ auto_prefix }}host" + volume: "{{ auto_prefix }}vol" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove host {{ auto_prefix }}host + infini_host: + name: "{{ auto_prefix }}host" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove host {{ auto_prefix }}host2 + infini_host: + name: "{{ auto_prefix }}host2" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove host {{ auto_prefix }}host again + infini_host: + name: "{{ auto_prefix }}host" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove export client for export /{{ auto_prefix }}export + infini_export_client: + client: 20.20.20.20 + state: absent + access_mode: "RO" + export: "/{{ auto_prefix }}export" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove export client for export /{{ auto_prefix }}export again + infini_export_client: + client: 20.20.20.20 + state: absent + access_mode: "RO" + export: "/{{ auto_prefix }}export" + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove export {{ auto_prefix }}export of file system {{ auto_prefix }}fs + infini_export: + name: "/{{ auto_prefix }}export" + filesystem: "{{ auto_prefix }}fs" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove export {{ auto_prefix }}export of file system {{ auto_prefix }}fs again + infini_export: + name: "/{{ auto_prefix }}export" + filesystem: "{{ auto_prefix }}fs" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove file system named {{ auto_prefix }}fs_default under pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs_default" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove file system named {{ auto_prefix }}fs_thick under pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs_thick" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove file system named {{ auto_prefix }}fs under pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove file system named {{ auto_prefix }}fs under pool {{ auto_prefix }}pool again + infini_fs: + name: "{{ auto_prefix }}fs" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove thin volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol" + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove thick volume {{ auto_prefix }}vol_thick under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol_thick" + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool again + infini_vol: + name: "{{ auto_prefix }}vol" + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove pool {{ auto_prefix }}pool + infini_pool: + name: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove snapshot {{ auto_prefix }}vol_snap + infini_vol: + name: "{{ auto_prefix }}vol_snap" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove file system named {{ auto_prefix }}fs again from now missing pool {{ auto_prefix }}pool + infini_fs: + name: "{{ auto_prefix }}fs" + size: 1GB + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove user {{ auto_prefix }}read_only_user + infini_user: + user_name: "{{ auto_prefix }}read_only_user" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove user {{ auto_prefix }}admin_user + infini_user: + user_name: "{{ auto_prefix }}admin_user" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove user {{ auto_prefix }}pool_admin_user + infini_user: + user_name: "{{ auto_prefix }}pool_admin_user" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove user {{ auto_prefix }}pool_admin_user again + infini_user: + user_name: "{{ auto_prefix }}pool_admin_user" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" diff --git a/ansible_collections/infinidat/infinibox/playbooks/test_remove_snapshots.yml b/ansible_collections/infinidat/infinibox/playbooks/test_remove_snapshots.yml new file mode 100644 index 000000000..0320d8bd4 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/playbooks/test_remove_snapshots.yml @@ -0,0 +1,32 @@ +--- +- hosts: localhost + gather_facts: false + collections: + - infinidat.infinibox + tasks: + + - name: POSITIVE test -> Remove thin volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool + infini_vol: + name: "{{ auto_prefix }}vol" + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: IDEMPOTENT test -> Remove volume {{ auto_prefix }}vol under pool {{ auto_prefix }}pool again + infini_vol: + name: "{{ auto_prefix }}vol" + pool: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" + + - name: POSITIVE test -> Remove pool {{ auto_prefix }}pool + infini_pool: + name: "{{ auto_prefix }}pool" + state: absent + user: "{{ user }}" + password: "{{ password }}" + system: "{{ system }}" diff --git a/ansible_collections/infinidat/infinibox/plugins/doc_fragments/infinibox.py b/ansible_collections/infinidat/infinibox/plugins/doc_fragments/infinibox.py new file mode 100644 index 000000000..f88a55ea4 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/doc_fragments/infinibox.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +class ModuleDocFragment(object): + """ + Standard Infinibox documentation fragment + """ + DOCUMENTATION = r''' +options: + system: + description: + - Infinibox Hostname or IPv4 Address. + type: str + required: true + user: + description: + - Infinibox User username with sufficient priveledges ( see notes ). + type: str + required: true + password: + description: + - Infinibox User password. + type: str + required: true +notes: + - This module requires infinisdk python library + - You must set INFINIBOX_USER and INFINIBOX_PASSWORD environment variables + if user and password arguments are not passed to the module directly + - Ansible uses the infinisdk configuration file C(~/.infinidat/infinisdk.ini) if no credentials are provided. + See U(http://infinisdk.readthedocs.io/en/latest/getting_started.html) + - All Infinidat modules support check mode (--check). However, a dryrun that creates + resources may fail if the resource dependencies are not met for a task. + For example, consider a task that creates a volume in a pool. + If the pool does not exist, the volume creation task will fail. + It will fail even if there was a previous task in the playbook that would have created the pool but + did not because the pool creation was also part of the dry run. +requirements: + - python2 >= 2.7 or python3 >= 3.6 + - infinisdk (https://infinisdk.readthedocs.io/en/latest/) +''' diff --git a/ansible_collections/infinidat/infinibox/plugins/filter/delta_time.yml b/ansible_collections/infinidat/infinibox/plugins/filter/delta_time.yml new file mode 100644 index 000000000..55735dad3 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/filter/delta_time.yml @@ -0,0 +1,27 @@ +DOCUMENTATION: + name: delta_time + author: Infinidat + version_added: 'historical' + short_description: Add a time delta to a datetime. + description: + - Add a time delta to a datetime. + - Return the calculated datetime. + positional: _input + options: + _datetime: + description: A datetime. + type: datetime + required: true + _kw_args: + description: Keyword args for the timedelta. + type: kwargs + required: true + +EXAMPLES: | + # Use within a jinja2 template. See test_create_resources.yml + {{ ansible_date_time.iso8601_micro | to_datetime(fmt) | infinidat.infinibox.delta_time(minutes=2) }} + +RETURN: + _value: + description: The input datetime with the deltatime added. + type: datetime diff --git a/ansible_collections/infinidat/infinibox/plugins/filter/psus_filters.py b/ansible_collections/infinidat/infinibox/plugins/filter/psus_filters.py new file mode 100644 index 000000000..5e140bdd8 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/filter/psus_filters.py @@ -0,0 +1,56 @@ +# -*- 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) 2022, Infinidat <info@infinidat.com> +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +from ansible.errors import AnsibleError +import datetime + + +def delta_time(dt, **kwargs): + """ + Add to the time. + Ref: https://docs.python.org/3.6/library/datetime.html#timedelta-objects + """ + return dt + datetime.timedelta(**kwargs) + + +class FilterModule(object): + """ + A filter look up class for custom filter plugins. + Ref: https://www.dasblinkenlichten.com/creating-ansible-filter-plugins/ + """ + def filters(self): + """ + Lookup the filter function by name and execute it. + """ + return self.filter_map + + filter_map = { + 'delta_time': delta_time, + } diff --git a/ansible_collections/infinidat/infinibox/plugins/module_utils/infinibox.py b/ansible_collections/infinidat/infinibox/plugins/module_utils/infinibox.py new file mode 100644 index 000000000..31df73d04 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/module_utils/infinibox.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 + +from ansible.module_utils.six import raise_from +try: + import ansible.module_utils.errors +except (ImportError, ModuleNotFoundError): + import errors # Used during "make dev-hack-module-[present, stat, absent]" + +try: + from infinisdk import InfiniBox, core + from infinisdk.core.exceptions import ObjectNotFound +except ImportError as imp_exc: + HAS_INFINISDK = False + INFINISDK_IMPORT_ERROR = imp_exc +else: + HAS_INFINISDK = True + INFINISDK_IMPORT_ERROR = None + +from functools import wraps +from os import environ +from os import path +from datetime import datetime + + +def unixMillisecondsToDate(unix_ms): + return (datetime.utcfromtimestamp(unix_ms / 1000.), 'UTC') + + +def api_wrapper(func): + """ Catch API Errors Decorator""" + @wraps(func) + def __wrapper(*args, **kwargs): + module = args[0] + try: + return func(*args, **kwargs) + except core.exceptions.APICommandException as e: + module.fail_json(msg=e.message) + except core.exceptions.SystemNotFoundException as e: + module.fail_json(msg=e.message) + except Exception: + raise + return __wrapper + + +def infinibox_argument_spec(): + """Return standard base dictionary used for the argument_spec argument in AnsibleModule""" + return dict( + system=dict(required=True), + user=dict(required=True), + password=dict(required=True, no_log=True), + ) + + +def infinibox_required_together(): + """Return the default list used for the required_together argument to AnsibleModule""" + return [['user', 'password']] + + +def merge_two_dicts(dict1, dict2): + """ + Merge two dicts into one and return. + result = {**dict1, **dict2} only works in py3.5+. + """ + result = dict1.copy() + result.update(dict2) + return result + + +@api_wrapper +def get_system(module): + """Return System Object or Fail""" + box = module.params['system'] + user = module.params.get('user', None) + password = module.params.get('password', None) + + if user and password: + system = InfiniBox(box, auth=(user, password), use_ssl=True) + elif environ.get('INFINIBOX_USER') and environ.get('INFINIBOX_PASSWORD'): + system = InfiniBox(box, + auth=(environ.get('INFINIBOX_USER'), + environ.get('INFINIBOX_PASSWORD')), + use_ssl=True) + elif path.isfile(path.expanduser('~') + '/.infinidat/infinisdk.ini'): + system = InfiniBox(box, use_ssl=True) + else: + module.fail_json(msg="You must set INFINIBOX_USER and INFINIBOX_PASSWORD environment variables or set username/password module arguments") + + try: + system.login() + except Exception: + module.fail_json(msg="Infinibox authentication failed. Check your credentials") + return system + + +@api_wrapper +def get_pool(module, system): + """ + Return Pool. Try key look up using 'pool', or if that fails, 'name'. + If the pool is not found, return None. + """ + try: + try: + name = module.params['pool'] + except KeyError: + name = module.params['name'] + return system.pools.get(name=name) + except Exception: + return None + + +@api_wrapper +def get_filesystem(module, system): + """Return Filesystem or None""" + try: + try: + filesystem = system.filesystems.get(name=module.params['filesystem']) + except KeyError: + filesystem = system.filesystems.get(name=module.params['name']) + return filesystem + except Exception: + return None + + +@api_wrapper +def get_export(module, system): + """Return export if found or None if not found""" + try: + try: + export_name = module.params['export'] + except KeyError: + export_name = module.params['name'] + + export = system.exports.get(export_path=export_name) + except ObjectNotFound as err: + return None + + return export + + +@api_wrapper +def get_volume(module, system): + """Return Volume or None""" + try: + try: + volume = system.volumes.get(name=module.params['name']) + except KeyError: + volume = system.volumes.get(name=module.params['volume']) + return volume + except Exception: + return None + + +@api_wrapper +def get_net_space(module, system): + """Return network space or None""" + try: + net_space = system.network_spaces.get(name=module.params['name']) + except (KeyError, ObjectNotFound): + return None + return net_space + + +@api_wrapper +def get_vol_sn(module, system): + """Return Volume or None""" + try: + try: + volume = system.volumes.get(serial=module.params['serial']) + except KeyError: + return None + return volume + except Exception: + return None + + +@api_wrapper +def get_host(module, system): + """Find a host by the name specified in the module""" + host = None + + for a_host in system.hosts.to_list(): + a_host_name = a_host.get_name() + try: + host_param = module.params['name'] + except KeyError: + host_param = module.params['host'] + + if a_host_name == host_param: + host = a_host + break + return host + + +@api_wrapper +def get_cluster(module, system): + """Find a cluster by the name specified in the module""" + cluster = None + # print("dir:", dir(system)) + + for a_cluster in system.host_clusters.to_list(): + a_cluster_name = a_cluster.get_name() + try: + cluster_param = module.params['name'] + except KeyError: + cluster_param = module.params['cluster'] + + if a_cluster_name == cluster_param: + cluster = a_cluster + break + return cluster + + +@api_wrapper +def get_user(module, system): + """Find a user by the user_name specified in the module""" + user = None + user_name = module.params['user_name'] + try: + user = system.users.get(name=user_name) + except ObjectNotFound: + pass + return user diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/__init__.py b/ansible_collections/infinidat/infinibox/plugins/modules/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/__init__.py diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_cluster.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_cluster.py new file mode 100644 index 000000000..fe682cf3c --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_cluster.py @@ -0,0 +1,298 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_cluster +version_added: '2.9.0' +short_description: Create, Delete and Modify Host Cluster on Infinibox +description: + - This module creates, deletes or modifies host clusters on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + name: + description: + - Cluster Name + required: true + type: str + state: + description: + - Creates/Modifies Cluster when present, removes when absent, or provides + details of a cluster when stat. + required: false + type: str + default: present + choices: [ "stat", "present", "absent" ] + cluster_hosts: + description: A list of hosts to add to a cluster when state is present. + required: false + type: list + elements: dict +extends_documentation_fragment: + - infinibox +''' + +EXAMPLES = r''' +- name: Create new cluster + infini_cluster: + name: foo_cluster + user: admin + password: secret + system: ibox001 +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +try: + from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + INFINISDK_IMPORT_ERROR, + api_wrapper, + infinibox_argument_spec, + get_system, + get_cluster, + unixMillisecondsToDate, + merge_two_dicts, + ) +except ModuleNotFoundError: + from infinibox import ( # Used when hacking + HAS_INFINISDK, + INFINISDK_IMPORT_ERROR, + api_wrapper, + infinibox_argument_spec, + get_system, + get_cluster, + unixMillisecondsToDate, + merge_two_dicts, + ) + +try: + from infi.dtypes.iqn import make_iscsi_name + HAS_INFI_MOD = True +except ImportError: + HAS_INFI_MOD = False + + +@api_wrapper +def get_host_by_name(system, host_name): + """Find a host by the name specified in the module""" + host = None + + for a_host in system.hosts.to_list(): + a_host_name = a_host.get_name() + if a_host_name == host_name: + host = a_host + break + return host + + +@api_wrapper +def create_cluster(module, system): + # print("create cluster") + changed = True + if not module.check_mode: + cluster = system.host_clusters.create(name=module.params['name']) + cluster_hosts = module.params['cluster_hosts'] + for cluster_host in cluster_hosts: + if cluster_host['host_cluster_state'] == 'present': + host = get_host_by_name(system, cluster_host['host_name']) + cluster.add_host(host) + # print("Added host {0} to cluster {1}".format(host.get_name, cluster.get_name())) + # else: + # print("Skipped adding (absent) host {0} to cluster {1}".format(host.get_name, cluster.get_name())) + return changed + + +@api_wrapper +def update_cluster(module, system, cluster): + # print("update cluster") + changed = False + + # e.g. of one host dict found in the module.params['cluster_hosts'] list: + # {host_name: <'some_name'>, host_cluster_state: <'present' or 'absent'>} + module_cluster_hosts = module.params['cluster_hosts'] + current_cluster_hosts_names = [host.get_name() for host in cluster.get_field('hosts')] + # print("current_cluster_hosts_names:", current_cluster_hosts_names) + for module_cluster_host in module_cluster_hosts: + module_cluster_host_name = module_cluster_host['host_name'] + # print("module_cluster_host_name:", module_cluster_host_name) + # Need to add host to cluster? + if module_cluster_host_name not in current_cluster_hosts_names: + if module_cluster_host['host_cluster_state'] == 'present': + host = get_host_by_name(system, module_cluster_host_name) + if not host: + msg = 'Cannot find host {0} to add to cluster {1}'.format( + module_cluster_host_name, + cluster.get_name(), + ) + module.fail_json(msg=msg) + cluster.add_host(host) + # print("Added host {0} to cluster {1}".format(host.get_name(), cluster.get_name())) + changed = True + # Need to remove host from cluster? + elif module_cluster_host_name in current_cluster_hosts_names: + if module_cluster_host['host_cluster_state'] == 'absent': + host = get_host_by_name(system, module_cluster_host_name) + if not host: + msg = 'Cannot find host {0} to add to cluster {1}'.format( + module_cluster_host_name, + cluster.get_name(), + ) + module.fail_json(msg=msg) + cluster.remove_host(host) + # print("Removed host {0} from cluster {1}".format(host.get_name(), cluster.get_name())) + changed = True + return changed + + +@api_wrapper +def delete_cluster(module, cluster): + if not cluster: + msg = "Cluster {0} not found".format(cluster.get_name()) + module.fail_json(msg=msg) + changed = True + if not module.check_mode: + cluster.delete() + return changed + + +def get_sys_cluster(module): + system = get_system(module) + cluster = get_cluster(module, system) + return (system, cluster) + + +def get_cluster_fields(cluster): + fields = cluster.get_fields(from_cache=True, raw_value=True) + created_at, created_at_timezone = unixMillisecondsToDate(fields.get('created_at', None)) + field_dict = dict( + hosts=[], + id=cluster.id, + created_at=created_at, + created_at_timezone=created_at_timezone, + ) + hosts = cluster.get_hosts() + for host in hosts: + host_dict = { + 'host_id': host.id, + 'host_name': host.get_name(), + } + field_dict['hosts'].append(host_dict) + return field_dict + + +def handle_stat(module): + system, cluster = get_sys_cluster(module) + cluster_name = module.params["name"] + if not cluster: + module.fail_json(msg='Cluster {0} not found'.format(cluster_name)) + field_dict = get_cluster_fields(cluster) + result = dict( + changed=False, + msg='Cluster stat found' + ) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + system, cluster = get_sys_cluster(module) + cluster_name = module.params["name"] + if not cluster: + changed = create_cluster(module, system) + msg = 'Cluster {0} created'.format(cluster_name) + module.exit_json(changed=changed, msg=msg) + else: + changed = update_cluster(module, system, cluster) + if changed: + msg = 'Cluster {0} updated'.format(cluster_name) + else: + msg = 'Cluster {0} required no changes'.format(cluster_name) + module.exit_json(changed=changed, msg=msg) + + +def handle_absent(module): + system, cluster = get_sys_cluster(module) + cluster_name = module.params["name"] + if not cluster: + changed = False + msg = "Cluster {0} already absent".format(cluster_name) + else: + changed = delete_cluster(module, cluster) + msg = "Cluster {0} removed".format(cluster_name) + module.exit_json(changed=changed, msg=msg) + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def check_options(module): + state = module.params['state'] + if state == 'present': + if module.params['cluster_hosts'] is None: + module.fail_json(msg='Option cluster_hosts, a list, must be provided') + + cluster_hosts = module.params['cluster_hosts'] + for host in cluster_hosts: + try: + # Check host has required keys + valid_keys = ['host_name', 'host_cluster_state'] + for valid_key in valid_keys: + not_used = host[valid_key] + # Check host has no unknown keys + if len(host.keys()) != len(valid_keys): + raise KeyError + except KeyError: + msg = 'With state present, all cluster_hosts ' \ + + 'require host_name and host_cluster_state key:values ' \ + + 'and no others' + module.fail_json(msg=msg) + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + name=dict(required=True), + state=dict(default='present', choices=['stat', 'present', 'absent']), + cluster_hosts=dict(required=False, type="list", elements="dict"), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFI_MOD: + module.fail_json(msg=missing_required_lib('infi.dtypes.iqn')) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib('infinisdk')) + + check_options(module) + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_export.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_export.py new file mode 100644 index 000000000..f83e9b1f1 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_export.py @@ -0,0 +1,277 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat(info@infinidat.com) +# 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 = r''' +--- +module: infini_export +version_added: '2.3.0' +short_description: Create, Delete or Modify NFS Exports on Infinibox +description: + - This module creates, deletes or modifies NFS exports on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + name: + description: + - Export name. Must start with a forward slash, e.g. name=/data. + required: true + type: str + state: + description: + - Creates/Modifies export when present, removes when absent, or provides + export details with stat. + required: false + default: "present" + choices: [ "stat", "present", "absent" ] + type: str + client_list: + description: + - List of dictionaries with client entries. See examples. + Check infini_export_client module to modify individual NFS client entries for export. + required: false + type: list + elements: dict + filesystem: + description: + - Name of exported file system. + required: true + type: str +extends_documentation_fragment: + - infinibox +requirements: + - munch +''' + +EXAMPLES = r''' +- name: Export bar filesystem under foo pool as /data + infini_export: + name: /data01 + filesystem: foo + state: present # Default + user: admin + password: secret + system: ibox001 + +- name: Get status of export bar filesystem under foo pool as /data + infini_export: + name: /data01 + filesystem: foo + state: stat + user: admin + password: secret + system: ibox001 + +- name: Remove export bar filesystem under foo pool as /data + infini_export: + name: /data01 + filesystem: foo + state: absent + user: admin + password: secret + system: ibox001 + +- name: Export and specify client list explicitly + infini_export: + name: /data02 + filesystem: foo + client_list: + - client: 192.168.0.2 + access: RW + no_root_squash: True + - client: 192.168.0.100 + access: RO + no_root_squash: False + - client: 192.168.0.10-192.168.0.20 + access: RO + no_root_squash: False + system: ibox001 + user: admin + password: secret +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_system, + get_filesystem, + get_export, + merge_two_dicts, +) + +MUNCH_IMP_ERR = None +try: + from munch import unmunchify + HAS_MUNCH = True +except ImportError: + HAS_MUNCH = False + MUNCH_IMPORT_ERROR = traceback.format_exc() + + +def transform(d): + return frozenset(d.items()) + + +def create_export(module, export, filesystem, system): + """ Create new filesystem or update existing one""" + if export: + raise AssertionError("Export {0} already exists".format(export.get_name())) + changed = False + + name = module.params['name'] + client_list = module.params['client_list'] + + if not module.check_mode: + export = system.exports.create(export_path=name, filesystem=filesystem) + if client_list: + export.update_permissions(client_list) + changed = True + return changed + + +@api_wrapper +def update_export(module, export, filesystem, system): + """ Create new filesystem or update existing one""" + if not export: + raise AssertionError("Export {0} does not exist and cannot be updated".format(export.get_name())) + + changed = False + + name = module.params['name'] + client_list = module.params['client_list'] + + if client_list: + # msg = "client_list: {0}, type: {1}".format(client_list, type(client_list)) + # module.fail_json(msg=msg) + if set(map(transform, unmunchify(export.get_permissions()))) \ + != set(map(transform, client_list)): + if not module.check_mode: + export.update_permissions(client_list) + changed = True + return changed + + +@api_wrapper +def delete_export(module, export): + """ Delete file system""" + if not module.check_mode: + export.delete() + changed = True + return changed + + +def get_sys_exp_fs(module): + system = get_system(module) + filesystem = get_filesystem(module, system) + export = get_export(module, system) + return (system, export, filesystem) + + +def get_export_fields(export): + fields = export.get_fields() # from_cache=True, raw_value=True) + export_id = fields.get('id', None) + permissions = fields.get('permissions', None) + enabled = fields.get('enabled', None) + field_dict = dict( + id=export_id, + permissions=permissions, + enabled=enabled, + ) + return field_dict + + +def handle_stat(module): + """ + Gather stats on export and return. Changed is always False. + """ + system, export, filesystem = get_sys_exp_fs(module) + if not export: + module.fail_json(msg='Export "{0}" of file system "{1}" not found'.format( + module.params['name'], + module.params['filesystem'], + )) + + field_dict = get_export_fields(export) + result = dict( + changed=False, + msg='File system stat found' + ) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + system, export, filesystem = get_sys_exp_fs(module) + if not filesystem: + module.fail_json(msg='File system {0} not found'.format(module.params['filesystem'])) + elif not export: + changed = create_export(module, export, filesystem, system) + module.exit_json(changed=changed, msg="File system export created") + else: + changed = update_export(module, export, filesystem, system) + module.exit_json(changed=changed, msg="File system export updated") + + +def handle_absent(module): + system, export, filesystem = get_sys_exp_fs(module) + if not export: + changed = False + msg = "Export of {0} already absent".format(module.params['filesystem']) + module.exit_json(changed=changed, msg=msg) + else: + changed = delete_export(module, export) + msg = "Export of {0} deleted".format(module.params['filesystem']) + module.exit_json(changed=changed, msg=msg) + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + name=dict(required=True), + state=dict(default='present', choices=['stat', 'present', 'absent']), + filesystem=dict(required=True), + client_list=dict(type='list', elements='dict') + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_MUNCH: + module.fail_json(msg=missing_required_lib('munch')) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib('infinisdk')) + + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_export_client.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_export_client.py new file mode 100644 index 000000000..d35705787 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_export_client.py @@ -0,0 +1,269 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_export_client +version_added: '2.3.0' +short_description: Create, Delete or Modify NFS Client(s) for existing exports on Infinibox +description: + - This module creates, deletes or modifys NFS client(s) for existing exports on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + client: + description: + - Client IP or Range. Ranges can be defined as follows + 192.168.0.1-192.168.0.254. + required: true + type: str + state: + description: + - Creates/Modifies client when present and removes when absent. + required: false + default: "present" + choices: [ "stat", "present", "absent" ] + type: str + access_mode: + description: + - Read Write or Read Only Access. + choices: [ "RW", "RO" ] + default: "RW" + required: false + type: str + no_root_squash: + description: + - Don't squash root user to anonymous. Will be set to "no" on creation if not specified explicitly. + type: bool + default: no + required: false + export: + description: + - Name of the export. + required: true + type: str +extends_documentation_fragment: + - infinibox +requirements: + - munch +''' + +EXAMPLES = r''' +- name: Make sure nfs client 10.0.0.1 is configured for export. Allow root access + infini_export_client: + client: 10.0.0.1 + access_mode: RW + no_root_squash: yes + export: /data + state: present # Default + user: admin + password: secret + system: ibox001 + +- name: Add multiple clients with RO access. Squash root privileges + infini_export_client: + client: "{{ item }}" + access_mode: RO + no_root_squash: no + export: /data + user: admin + password: secret + system: ibox001 + with_items: + - 10.0.0.2 + - 10.0.0.3 +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_system, + get_export, + merge_two_dicts, +) + +MUNCH_IMP_ERR = None +try: + from munch import Munch, unmunchify + HAS_MUNCH = True +except ImportError: + MUNCH_IMPORT_ERROR = traceback.format_exc() + HAS_MUNCH = False + + +@api_wrapper +def update_client(module, export): + """ + Update export client list. Note that this will replace existing clients. + """ + + changed = False + + client = module.params['client'] + access_mode = module.params['access_mode'] + no_root_squash = module.params['no_root_squash'] + + client_list = export.get_permissions() + client_not_in_list = True + + for item in client_list: + if item.client == client: # Update client + client_not_in_list = False + if item.access != access_mode: + item.access = access_mode + changed = True + if item.no_root_squash is not no_root_squash: + item.no_root_squash = no_root_squash + changed = True + + # If access_mode and/or no_root_squash not passed as arguments to the module, + # use access_mode with RW value and set no_root_squash to False + if client_not_in_list: # Create client + changed = True + client_list.append(Munch(client=client, access=access_mode, no_root_squash=no_root_squash)) + + if changed: + for index, item in enumerate(client_list): + client_list[index] = unmunchify(item) + if not module.check_mode: + export.update_permissions(client_list) + + return changed + + +@api_wrapper +def delete_client(module, export): + """Update export client list""" + if export is None and module.params['state'] == 'absent': + module.exit_json(changed=False) + + changed = False + + client = module.params['client'] + client_list = export.get_permissions() + + for index, item in enumerate(client_list): + if item.client == client: + changed = True + del client_list[index] + + if changed: + for index, item in enumerate(client_list): + client_list[index] = unmunchify(item) + if not module.check_mode: + export.update_permissions(client_list) + + return changed + + +def get_sys_exp(module): + system = get_system(module) + export = get_export(module, system) + return (system, export) + + +def get_export_client_fields(export, client_name): + fields = export.get_fields() # from_cache=True, raw_value=True) + permissions = fields.get('permissions', None) + for munched_perm in permissions: + perm = unmunchify(munched_perm) + if perm['client'] == client_name: # Found client + field_dict = dict( + access_mode=perm['access'], + no_root_squash=perm['no_root_squash'], + ) + return field_dict + raise AssertionError("No client {0} match to exports found".format(client_name)) + + +def handle_stat(module): + system, export = get_sys_exp(module) + if not export: + module.fail_json(msg='Export {0} not found'.format(module.params['export'])) + client_name = module.params['client'] + field_dict = get_export_client_fields(export, client_name) + result = dict( + changed=False, + msg='Export client stat found' + ) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + system, export = get_sys_exp(module) + if not export: + msg = 'Export {0} not found'.format(module.params['export']) + module.fail_json(msg=msg) + + changed = update_client(module, export) + msg = "Export client updated" + module.exit_json(changed=changed, msg=msg) + + +def handle_absent(module): + system, export = get_sys_exp(module) + if not export: + changed = False + msg = "Export client already absent" + module.exit_json(changed=False, msg=msg) + else: + changed = delete_client(module, export) + msg = "Export client removed" + module.exit_json(changed=changed, msg=msg) + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + client=dict(required=True), + state=dict(default='present', choices=['stat', 'present', 'absent']), + access_mode=dict(choices=['RO', 'RW'], default='RW', type="str"), + no_root_squash=dict(type='bool', default='no'), + export=dict(required=True) + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_MUNCH: + module.fail_json(msg=missing_required_lib('munch'), + exception=MUNCH_IMPORT_ERROR) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib('infinisdk')) + + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_fs.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_fs.py new file mode 100644 index 000000000..f9cd2bd56 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_fs.py @@ -0,0 +1,250 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_fs +version_added: '2.3.0' +short_description: Create, Delete or Modify filesystems on Infinibox +description: + - This module creates, deletes or modifies filesystems on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + name: + description: + - File system name. + required: true + type: str + state: + description: + - Creates/Modifies file system when present or removes when absent. + required: false + default: present + choices: [ "stat", "present", "absent" ] + type: str + thin_provision: + description: + - Whether the master file system should be thin or thick provisioned. + required: false + default: true + type: bool + pool: + description: + - Pool that will host file system. + required: true + type: str + size: + description: + - File system size in MB, GB or TB units. See examples. + required: false + type: str +extends_documentation_fragment: + - infinibox +requirements: + - capacity +''' + +EXAMPLES = r''' +- name: Create new file system named foo under pool named bar + infini_fs: + name: foo + size: 1TB + pool: bar + thin_provision: true + state: present + user: admin + password: secret + system: ibox001 +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +try: + from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_pool, + get_system, + get_filesystem + ) +except ModuleNotFoundError: + from infinibox import ( # Used when hacking + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_pool, + get_system, + get_filesystem + ) + +CAPACITY_IMP_ERR = None +try: + from capacity import KiB, Capacity + HAS_CAPACITY = True +except ImportError: + HAS_CAPACITY = False + + +@api_wrapper +def create_filesystem(module, system): + """Create Filesystem""" + changed = True + if not module.check_mode: + if module.params['thin_provision']: + provisioning = 'THIN' + else: + provisioning = 'THICK' + filesystem = system.filesystems.create( + name=module.params['name'], + pool=get_pool(module, system), + provtype=provisioning, + ) + + if module.params['size']: + size = Capacity(module.params['size']).roundup(64 * KiB) + filesystem.update_size(size) + return changed + + +@api_wrapper +def update_filesystem(module, filesystem): + """Update Filesystem""" + changed = False + if module.params['size']: + size = Capacity(module.params['size']).roundup(64 * KiB) + if filesystem.get_size() != size: + if not module.check_mode: + filesystem.update_size(size) + changed = True + + provisioning = str(filesystem.get_provisioning()) + if provisioning == 'THICK' and module.params['thin_provision']: + if not module.check_mode: + filesystem.update_provisioning('THIN') + changed = True + if provisioning == 'THIN' and not module.params['thin_provision']: + if not module.check_mode: + filesystem.update_provisioning('THICK') + changed = True + return changed + + +@api_wrapper +def delete_filesystem(module, filesystem): + """ Delete Filesystem""" + if not module.check_mode: + filesystem.delete() + module.exit_json(changed=True) + + +def get_sys_pool_fs(module): + system = get_system(module) + pool = get_pool(module, system) + filesystem = get_filesystem(module, system) + return (system, pool, filesystem) + + +def handle_stat(module): + system, pool, filesystem = get_sys_pool_fs(module) + if not pool: + module.fail_json(msg='Pool {0} not found'.format(module.params['pool'])) + if not filesystem: + module.fail_json(msg='File system {0} not found'.format(module.params['name'])) + fields = filesystem.get_fields() # from_cache=True, raw_value=True) + name = fields.get("name", None) + used = fields.get('used_size', None) + filesystem_id = fields.get('id', None) + provisioning = fields.get('provisioning', None) + + result = dict( + changed=False, + name=name, + size=str(filesystem.get_size()), + used=str(used), + filesystem_id=filesystem_id, + provisioning=provisioning, + msg='File system stat found' + ) + module.exit_json(**result) + + +def handle_present(module): + system, pool, filesystem = get_sys_pool_fs(module) + if not pool: + module.fail_json(msg='Pool {0} not found'.format(module.params['pool'])) + if not filesystem: + changed = create_filesystem(module, system) + module.exit_json(changed=changed, msg="File system created") + else: + changed = update_filesystem(module, filesystem) + module.exit_json(changed=changed, msg="File system updated") + + +def handle_absent(module): + system, pool, filesystem = get_sys_pool_fs(module) + if not pool or not filesystem: + module.exit_json(changed=False, msg="File system already absent") + else: + changed = delete_filesystem(module, filesystem) + module.exit_json(changed=changed, msg="File system removed") + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + name=dict(required=True), + state=dict(default='present', choices=['stat', 'present', 'absent']), + pool=dict(required=True), + size=dict(), + thin_provision=dict(type=bool, default=True), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib('infinisdk')) + + if not HAS_CAPACITY: + module.fail_json(msg=missing_required_lib('capacity')) + + if module.params['size']: + try: + Capacity(module.params['size']) + except Exception: + module.fail_json(msg='size (Physical Capacity) should be defined in MB, GB, TB or PB units') + + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_host.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_host.py new file mode 100644 index 000000000..68d78546e --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_host.py @@ -0,0 +1,192 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_host +version_added: '2.3.0' +short_description: Create, Delete or Modify Hosts on Infinibox +description: + - This module creates, deletes or modifies hosts on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + name: + description: + - Host Name + required: true + state: + description: + - Creates/Modifies Host when present or removes when absent + required: false + default: present + choices: [ "stat", "present", "absent" ] +extends_documentation_fragment: + - infinibox +''' + +EXAMPLES = r''' +- name: Create new host + infini_host: + name: foo.example.com + user: admin + password: secret + system: ibox001 +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +from infi.dtypes.iqn import make_iscsi_name +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_system, + get_host, + unixMillisecondsToDate, + merge_two_dicts, +) + + +@api_wrapper +def create_host(module, system): + + changed = True + + if not module.check_mode: + host = system.hosts.create(name=module.params['name']) + return changed + + +@api_wrapper +def update_host(module, host): + changed = False + return changed + + +@api_wrapper +def delete_host(module, host): + changed = True + if not module.check_mode: + # May raise APICommandFailed if mapped, etc. + host.delete() + return changed + + +def get_sys_host(module): + system = get_system(module) + host = get_host(module, system) + return (system, host) + + +def get_host_fields(host): + fields = host.get_fields(from_cache=True, raw_value=True) + created_at, created_at_timezone = unixMillisecondsToDate(fields.get('created_at', None)) + field_dict = dict( + created_at=created_at, + created_at_timezone=created_at_timezone, + id=host.id, + iqns=[], + luns=[], + ports=[], + wwns=[], + ) + luns = host.get_luns() + for lun in luns: + field_dict['luns'].append({'lun_id': lun.id, + 'lun_volume_id': lun.volume.id, + 'lun_volume_name': lun.volume.get_name(), + }) + ports = host.get_ports() + for port in ports: + if str(type(port)) == "<class 'infi.dtypes.wwn.WWN'>": + field_dict['wwns'].append(str(port)) + if str(type(port)) == "<class 'infi.dtypes.iqn.IQN'>": + field_dict['iqns'].append(str(port)) + return field_dict + + +def handle_stat(module): + system, host = get_sys_host(module) + host_name = module.params["name"] + if not host: + module.fail_json(msg='Host {0} not found'.format(host_name)) + field_dict = get_host_fields(host) + result = dict( + changed=False, + msg='Host stat found' + ) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + system, host = get_sys_host(module) + host_name = module.params["name"] + if not host: + changed = create_host(module, system) + msg = 'Host {0} created'.format(host_name) + module.exit_json(changed=changed, msg=msg) + else: + changed = update_host(module, host) + msg = 'Host {0} updated'.format(host_name) + module.exit_json(changed=changed, msg=msg) + + +def handle_absent(module): + system, host = get_sys_host(module) + host_name = module.params["name"] + if not host: + msg = "Host {0} already absent".format(host_name) + module.exit_json(changed=False, msg=msg) + else: + changed = delete_host(module, host) + msg = "Host {0} removed".format(host_name) + module.exit_json(changed=changed, msg=msg) + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + name=dict(required=True), + state=dict(default='present', choices=['stat', 'present', 'absent']), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib('infinisdk')) + + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_map.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_map.py new file mode 100644 index 000000000..e3757e021 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_map.py @@ -0,0 +1,655 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_map +version_added: '2.9.0' +short_description: Create and Delete mapping of a volume to a host or cluster on Infinibox +description: + - This module creates or deletes mappings of volumes to hosts or clusters + on Infinibox. + - For Linux hosts, after calling this module, the playbook should execute "rescan-scsi-bus.sh" on the host when creating mappings. + - When removing mappings "rescan-scsi-bus.sh --remove" should be called. + - For Windows hosts, consider using "'rescan' | diskpart" or "Update-HostStorageCache". +author: David Ohlemacher (@ohlemacher) +options: + host: + description: + - Host Name + required: false + cluster: + description: + - Cluster Name + required: false + state: + description: + - Creates mapping when present or removes when absent, or provides + details of a mapping when stat. + required: false + default: present + choices: [ "stat", "present", "absent" ] + type: str + volume: + description: + - Volume name to map to the host. + required: true + lun: + description: + - Volume lun. +extends_documentation_fragment: + - infinibox +''' + +EXAMPLES = r''' +- name: Map a volume to an existing host + infini_map: + host: foo.example.com + volume: bar + state: present # Default + user: admin + password: secret + system: ibox001 + +- name: Map a volume to an existing cluster + infini_map: + cluster: test-cluster + volume: bar + state: present # Default + user: admin + password: secret + system: ibox001 + +- name: Unmap volume bar from host foo.example.com + infini_map: + host: foo.example.com + volume: bar + state: absent + system: ibox01 + user: admin + password: secret + +- name: Stat mapping of volume bar to host foo.example.com + infini_map: + host: foo.example.com + volume: bar + state: stat + system: ibox01 + user: admin + password: secret +''' + + +# RETURN = r''' # ''' + +import traceback +# import sh + +# rescan_scsi = sh.Command("rescan-scsi-bus.sh") +# rescan_scsi_remove = rescan_scsi.bake("--remove") + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + get_cluster, + get_host, + get_pool, + get_system, + get_volume, + infinibox_argument_spec, + merge_two_dicts +) + +try: + from infinisdk.core.exceptions import APICommandFailed, ObjectNotFound +except ImportError: + pass # Handled by HAS_INFINISDK from module_utils + + +def vol_is_mapped_to_host(volume, host): + volume_fields = volume.get_fields() + volume_id = volume_fields.get('id') + host_luns = host.get_luns() + # print('volume id: {0}'.format(volume_id)) + # print('host luns: {0}'.format(str(host_luns))) + for lun in host_luns: + if lun.volume == volume: + # print('found mapped volume: {0}'.format(volume)) + return True + return False + + +def vol_is_mapped_to_cluster(volume, cluster): + volume_fields = volume.get_fields() + volume_id = volume_fields.get('id') + cluster_luns = cluster.get_luns() + # print('volume id: {0}'.format(volume_id)) + # print('host luns: {0}'.format(str(host_luns))) + + for lun in cluster_luns: + if lun.volume == volume: + # print('found mapped volume: {0}'.format(volume)) + return True + return False + + +def find_host_lun_use(module, host, volume): + check_result = {'lun_used': False, 'lun_volume_matches': False} + desired_lun = module.params['lun'] + + if desired_lun: + for host_lun in host.get_luns(): + if desired_lun == host_lun.lun: + if host_lun.volume == volume: + check_result = {'lun_used': True, 'lun_volume_matches': True} + else: + check_result = {'lun_used': True, 'lun_volume_matches': False} + + return check_result + + +def find_cluster_lun_use(module, cluster, volume): + check_result = {'lun_used': False, 'lun_volume_matches': False} + desired_lun = module.params['lun'] + + if desired_lun: + for cluster_lun in cluster.get_luns(): + if desired_lun == cluster.lun: + if cluster.volume == volume: + check_result = {'lun_used': True, 'lun_volume_matches': True} + else: + check_result = {'lun_used': True, 'lun_volume_matches': False} + + return check_result + + +def find_host_lun(host, volume): + found_lun = None + luns = host.get_luns() + + for lun in luns: + if lun.volume == volume: + found_lun = lun.lun + return found_lun + + +def find_cluster_lun(cluster, volume): + found_lun = None + luns = cluster.get_luns() + + for lun in luns: + if lun.volume == volume: + found_lun = lun.lun + return found_lun + + +@api_wrapper +def create_mapping(module, system): + """ + Create mapping of volume to host or cluster. If already mapped, exit_json with changed False. + """ + + host_name = module.params['host'] + cluster_name = module.params['cluster'] + host = get_host(module, system) + cluster = get_cluster(module, system) + + if host: + changed = create_mapping_to_host(module, system) + elif cluster: + changed = create_mapping_to_cluster(module, system) + else: + msg = "A programming error has occurred in create_mapping()" + module.fail_json(msg=msg) + + # if changed: + # with sh.contrib.sudo: + # print("rescanning") + # rescan_scsi() + + return changed + + +@api_wrapper +def create_mapping_to_cluster(module, system): + """ + Create mapping of volume to cluster. If already mapped, exit_json with changed False. + """ + changed = False + + cluster = get_cluster(module, system) + volume = get_volume(module, system) + + lun_use = find_cluster_lun_use(module, cluster, volume) + if lun_use['lun_used']: + msg = "Cannot create mapping of volume '{0}' to cluster '{1}' using lun '{2}'. Lun in use.".format( + volume.get_name(), + cluster.get_name(), + module.params['lun']) + module.fail_json(msg=msg) + + try: + desired_lun = module.params['lun'] + if not module.check_mode: + cluster.map_volume(volume, lun=desired_lun) + changed = True + except APICommandFailed as err: + if "is already mapped" not in str(err): + module.fail_json('Cannot map volume {0} to cluster {1}: {2}. Already mapped.'.format( + module.params['volume'], + module.params['cluster'], + str(err))) + + return changed + + +@api_wrapper +def create_mapping_to_host(module, system): + """ + Create mapping of volume to host. If already mapped, exit_json with changed False. + """ + changed = False + + host = system.hosts.get(name=module.params['host']) + volume = get_volume(module, system) + + lun_use = find_host_lun_use(module, host, volume) + if lun_use['lun_used']: + msg = "Cannot create mapping of volume '{0}' to host '{1}' using lun '{2}'. Lun in use.".format( + volume.get_name(), + host.get_name(), + module.params['lun']) + module.fail_json(msg=msg) + + try: + desired_lun = module.params['lun'] + if not module.check_mode: + host.map_volume(volume, lun=desired_lun) + changed = True + except APICommandFailed as err: + if "is already mapped" not in str(err): + module.fail_json('Cannot map volume {0} to host {1}: {2}. Already mapped.'.format( + module.params['volume'], + module.params['host'], + str(err))) + + return changed + + +@api_wrapper +def update_mapping_to_host(module, system): + host = get_host(module, system) + volume = get_volume(module, system) + desired_lun = module.params['lun'] + + if not vol_is_mapped_to_host(volume, host): + msg = "Volume {0} is not mapped to host {1}".format( + volume.get_name(), + host.get_name(), + ) + module.fail_json(msg=msg) + + if desired_lun: + found_lun = find_host_lun(host, volume) + if found_lun != desired_lun: + msg = "Cannot change the lun from '{0}' to '{1}' for existing mapping of volume '{2}' to host '{3}'".format( + found_lun, + desired_lun, + volume.get_name(), + host.get_name()) + module.fail_json(msg=msg) + + changed = False + return changed + + +@api_wrapper +def update_mapping_to_cluster(module, system): + cluster = get_cluster(module, system) + volume = get_volume(module, system) + desired_lun = module.params['lun'] + + if not vol_is_mapped_to_cluster(volume, cluster): + msg = "Volume {0} is not mapped to cluster {1}".format( + volume.get_name(), + cluster.get_name(), + ) + module.fail_json(msg=msg) + + if desired_lun: + found_lun = find_cluster_lun(cluster, volume) + if found_lun != desired_lun: + msg = "Cannot change the lun from '{0}' to '{1}' for existing mapping of volume '{2}' to cluster '{3}'".format( + found_lun, + desired_lun, + volume.get_name(), + cluster.get_name()) + module.fail_json(msg=msg) + + changed = False + return changed + + +@api_wrapper +def delete_mapping(module, system): + host = get_host(module, system) + cluster = get_cluster(module, system) + if host: + changed = delete_mapping_to_host(module, system) + elif cluster: + changed = delete_mapping_to_cluster(module, system) + else: + msg = "A programming error has occurred in delete_mapping()" + module.fail_json(msg=msg) + + # if changed: + # with sh.contrib.sudo: + # print("rescanning --remove") + # rescan_scsi_remove() + + return changed + + +@api_wrapper +def delete_mapping_to_host(module, system): + """ + Remove mapping of volume from host. If the either the volume or host + do not exist, then there should be no mapping to unmap. If unmapping + generates a key error with 'has no logical units' in its message, then + the volume is not mapped. Either case, return changed=False. + """ + changed = False + msg = "" + + if not module.check_mode: + volume = get_volume(module, system) + host = get_host(module, system) + + if volume and host: + try: + existing_lun = find_host_lun(host, volume) + host.unmap_volume(volume) + changed = True + msg = "Volume '{0}' was unmapped from host '{1}' freeing lun '{2}'".format( + module.params['volume'], + module.params['host'], + existing_lun, + ) + + except KeyError as err: + if 'has no logical units' not in str(err): + module.fail_json('Cannot unmap volume {0} from host {1}: {2}'.format( + module.params['volume'], + module.params['host'], + str(err))) + else: + msg = "Volume {0} was not mapped to host {1} and so unmapping was not executed".format( + module.params['volume'], + module.params['host'], + ) + else: + msg = "Either volume {0} or host {1} does not exist. Unmapping was not executed".format( + module.params['volume'], + module.params['host'], + ) + else: # check_mode + changed = True + + module.exit_json(msg=msg, changed=changed) + + +@api_wrapper +def delete_mapping_to_cluster(module, system): + """ + Remove mapping of volume from cluster. If the either the volume or cluster + do not exist, then there should be no mapping to unmap. If unmapping + generates a key error with 'has no logical units' in its message, then + the volume is not mapped. Either case, return changed=False. + """ + changed = False + msg = "" + + if not module.check_mode: + volume = get_volume(module, system) + cluster = get_cluster(module, system) + + if volume and cluster: + try: + existing_lun = find_cluster_lun(cluster, volume) + cluster.unmap_volume(volume) + changed = True + msg = "Volume '{0}' was unmapped from cluster '{1}' freeing lun '{2}'".format( + module.params['volume'], + module.params['cluster'], + existing_lun, + ) + except KeyError as err: + if 'has no logical units' not in str(err): + module.fail_json('Cannot unmap volume {0} from cluster {1}: {2}'.format( + module.params['volume'], + module.params['cluster'], + str(err))) + else: + msg = "Volume {0} was not mapped to cluster {1} and so unmapping was not executed".format( + module.params['volume'], + module.params['cluster'], + ) + else: + msg = "Either volume {0} or cluster {1} does not exist. Unmapping was not executed".format( + module.params['volume'], + module.params['cluster'], + ) + else: # check_mode + changed = True + + module.exit_json(msg=msg, changed=changed) + + +def get_sys_vol_host_cluster(module): + system = get_system(module) + volume = get_volume(module, system) + host = get_host(module, system) + cluster = get_cluster(module, system) + return (system, volume, host, cluster) + + +def get_sys_vol_cluster(module): + system = get_system(module) + volume = get_volume(module, system) + cluster = get_cluster(module, system) + return (system, volume, cluster) + + +def get_mapping_fields(volume, host_or_cluster): + luns = host_or_cluster.get_luns() + for lun in luns: + if volume.get_name() == lun.volume.get_name(): + field_dict = dict( + id=lun.id, + ) + return field_dict + return dict() + + +def handle_stat(module): + system, volume, host, cluster = get_sys_vol_host_cluster(module) + volume_name = module.params['volume'] + + host_name = module.params['host'] + if not host_name: + host_name = "not specified" + + cluster_name = module.params['cluster'] + if not cluster_name: + cluster_name = "not specified" + + if not volume: + module.fail_json(msg='Volume {0} not found'.format(volume_name)) + if not host and not cluster: + module.fail_json(msg='Neither host [{0}] nor cluster [{1}] found'.format(host_name, cluster_name)) + if (not host or not vol_is_mapped_to_host(volume, host)) \ + and (not cluster or not vol_is_mapped_to_cluster(volume, cluster)): + msg = 'Volume {0} is mapped to neither host {1} nor cluster {2}'.format(volume_name, host_name, cluster_name) + module.fail_json(msg=msg) + if host: + found_lun = find_host_lun(host, volume) + field_dict = get_mapping_fields(volume, host) + if found_lun is not None: + msg = 'Volume {0} is mapped to host {1} using lun {2}'.format(volume_name, host_name, found_lun), + result = dict( + changed=False, + volume_lun=found_lun, + msg=msg, + ) + else: + msg = 'Volume {0} is not mapped to host {1}'.format(volume_name, host_name) + module.fail_json(msg=msg) + elif cluster: + found_lun = find_cluster_lun(cluster, volume) + field_dict = get_mapping_fields(volume, cluster) + if found_lun is not None: + msg = 'Volume {0} is mapped to cluster {1} using lun {2}'.format(volume_name, cluster_name, found_lun) + result = dict( + changed=False, + volume_lun=found_lun, + msg=msg, + ) + else: + msg = 'Volume {0} is not mapped to cluster {1}'.format(volume_name, cluster_name) + module.fail_json(msg=msg) + else: + msg = 'A programming error has occurred in handle_stat()' + module.fail_json(msg=msg) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + system, volume, host, cluster = get_sys_vol_host_cluster(module) + volume_name = module.params['volume'] + host_name = module.params['host'] + cluster_name = module.params['cluster'] + if not volume: + module.fail_json(changed=False, msg='Volume {0} not found'.format(volume_name)) + if not host and not cluster: + if not host_name: + host_name = "not specified" + if not cluster_name: + cluster_name = "not specified" + module.fail_json(changed=False, msg='Neither host [{0}] nor cluster [{1}] found'.format(host_name, cluster_name)) + if host: + if not vol_is_mapped_to_host(volume, host): + changed = create_mapping(module, system) + # TODO: Why is find_host_lun() returning None after creating the mapping? + # host.get_luns() returns an empty list, why? + # existing_lun = find_host_lun(host, volume) + # msg = "Volume '{0}' map to host '{1}' created using lun '{2}'".format( + # volume.get_name(), + # host.get_name(), + # existing_lun, + # ) + msg = "Volume '{0}' map to host '{1}' created".format(volume_name, host_name) + else: + changed = update_mapping_to_host(module, system) + existing_lun = find_host_lun(host, volume) + msg = "Volume '{0}' map to host '{1}' already exists using lun '{2}'".format(volume_name, host_name, existing_lun) + elif cluster: + if not vol_is_mapped_to_cluster(volume, cluster): + changed = create_mapping(module, system) + # TODO: Why is find_host_lun() returning None after creating the mapping? + # host.get_luns() returns an empty list, why? + # existing_lun = find_host_lun(host, volume) + # msg = "Volume '{0}' map to host '{1}' created using lun '{2}'".format( + # volume.get_name(), + # host.get_name(), + # existing_lun, + # ) + msg = "Volume '{0}' map to cluster '{1}' created".format(volume_name, cluster_name) + else: + changed = update_mapping_to_cluster(module, system) + existing_lun = find_cluster_lun(cluster, volume) + msg = "Volume '{0}' map to cluster '{1}' already exists using lun '{2}'".format(volume_name, cluster_name, existing_lun) + + result = dict( + changed=changed, + msg=msg, + ) + module.exit_json(**result) + + +def handle_absent(module): + system, volume, host, cluster = get_sys_vol_host_cluster(module) + volume_name = module.params['volume'] + host_name = module.params['host'] + cluster_name = module.params['cluster'] + if not volume or (not host and not cluster): + module.exit_json(changed=False, msg='Mapping of volume {0} to host {1} or cluster {2} already absent'.format(volume_name, host_name, cluster_name)) + else: + changed = delete_mapping(module, system) + module.exit_json(changed=changed, msg="Mapping removed") + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def check_parameters(module): + volume_name = module.params['volume'] + host_name = module.params['host'] + cluster_name = module.params['cluster'] + if host_name and cluster_name: + msg = "infini_map requires a host or a cluster but not both to be provided" + module.fail_json(msg=msg) + + if not host_name and not cluster_name: + msg = "infini_map requires a host or a cluster to be provided" + module.fail_json(msg=msg) + + +def main(): + """ + Gather auguments and manage mapping of vols to hosts. + """ + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + host=dict(required=False, default=""), + cluster=dict(required=False, default=""), + state=dict(default='present', choices=['stat', 'present', 'absent']), + volume=dict(required=True), + lun=dict(type=int), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib('infinisdk')) + + check_parameters(module) + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_network_space.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_network_space.py new file mode 100644 index 000000000..013d86e5e --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_network_space.py @@ -0,0 +1,424 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_network_space +version_added: '2.12.0' +short_description: Create, Delete and Modify network spaces on Infinibox +description: + - This module creates, deletes or modifies network spaces on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + name: + description: + - Network space name + required: true + state: + description: + - Creates/Modifies network spaces when present. Removes when absent. Shows status when stat. + required: false + default: present + choices: [ "stat", "present", "absent" ] + interfaces: + description: + - A list of interfaces for the space. + required: false + type: list + elements: str + service: + description: + - Choose a service. + required: false + default: "replication" + choices: ["replication", "NAS", "iSCSI"] + mtu: + description: + - Set an MTU. If not specified, defaults to 1500 bytes. + required: false + type: int + network: + description: + - Starting IP address. + required: false + type: str + netmask: + description: + - Network mask. + required: false + type: int + ips: + description: + - List of IPs. + required: false + default: [] + type: list + elements: str + rate_limit: + description: + - Specify the throughput limit per node. + - The limit is specified in Mbps, megabits per second (not megabytes). + - Note the limit affects NFS, iSCSI and async-replication traffic. + - It does not affect sync-replication or active-active traffic. + required: false + type: int + +extends_documentation_fragment: + - infinibox +''' + +EXAMPLES = r''' +- name: Create new network space + infini_network_space: + name: iSCSI + state: present + interfaces: + - 1680 + - 1679 + - 1678 + service: ISCSI_SERVICE + netmask: 19 + network: 172.31.32.0 + default_gateway: 172.31.63.254 + ips: + - 172.31.32.145 + - 172.31.32.146 + - 172.31.32.147 + - 172.31.32.148 + - 172.31.32.149 + - 172.31.32.150 + user: admin + password: secret + system: ibox001 +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_system, + unixMillisecondsToDate, + merge_two_dicts, + get_net_space, +) + +try: + from infinisdk.core.exceptions import APICommandFailed + from infinisdk.core.exceptions import ObjectNotFound + from infi.dtypes.iqn import make_iscsi_name +except ImportError: + pass # Handled by HAS_INFINISDK from module_utils + + +@api_wrapper +def create_empty_network_space(module, system): + # Create network space + network_space_name = module.params["name"] + service = module.params["service"] + rate_limit = module.params["rate_limit"] + mtu = module.params["mtu"] + network_config = { + "netmask": module.params["netmask"], + "network": module.params["network"], + "default_gateway": module.params["default_gateway"], + } + interfaces = module.params["interfaces"] + + # print("Creating network space {0}".format(network_space_name)) + product_id = system.api.get('system/product_id') + # print("api: {0}".format(product_id.get_result())) + + net_create_url = "network/spaces" + net_create_data = { + "name": network_space_name, + "service": service, + "network_config": network_config, + "interfaces": interfaces, + } + if rate_limit: + net_create_data["rate_limit"] = rate_limit + if mtu: + net_create_data["mtu"] = mtu + + net_create = system.api.post( + path=net_create_url, + data=net_create_data + ) + # print("net_create: {0}".format(net_create)) + + +@api_wrapper +def find_network_space_id(module, system): + """ + Find the ID of this network space + """ + network_space_name = module.params["name"] + net_id_url = "network/spaces?name={0}&fields=id".format(network_space_name) + net_id = system.api.get( + path=net_id_url + ) + result = net_id.get_json()['result'][0] + space_id = result['id'] + # print("Network space has ID {0}".format(space_id)) + return space_id + + +@api_wrapper +def add_ips_to_network_space(module, system, space_id): + network_space_name = module.params["name"] + # print("Adding IPs to network space {0}".format(network_space_name)) + + ips = module.params["ips"] + for ip in ips: + ip_url = "network/spaces/{0}/ips".format(space_id) + ip_data = ip + ip_add = system.api.post( + path=ip_url, + data=ip_data + ) + # print("add_ips json: {0}".format(ip_add.get_json())) + result = ip_add.get_json()['result'] + # print("add ip result: {0}".format(result)) + + +@api_wrapper +def create_network_space(module, system): + if not module.check_mode: + # Create space + create_empty_network_space(module, system) + # Find space's ID + space_id = find_network_space_id(module, system) + # Add IPs to space + add_ips_to_network_space(module, system, space_id) + + changed = True + else: + changed = False + + return changed + + +def update_network_space(module, system): + """ + Update network space. + TODO - This is incomplete and will not update the space. + It will instead return changed=False and a message. + To implement this we will need to find the existing space. + For each field that we support updating, we need to compare existing + to new values and if different update. We will need to iterate + over the settings or we will receive: + Status: 400 + Code: NOT_SUPPORTED_MULTIPLE_UPDATE + """ + changed = False + msg = "Update is not supported yet" + module.exit_json(changed=changed, msg=msg) + + # TODO Everything below is incomplete + # Update network space + network_space_name = module.params["name"] + service = module.params["service"] + network_config = { + "netmask": module.params["netmask"], + "network": module.params["network"], + "default_gateway": module.params["default_gateway"], + } + interfaces = module.params["interfaces"] + + # print("Updating network space {0}".format(network_space_name)) + + # Find space's ID + space_id = find_network_space_id(module, system) + + net_url = "network/spaces/{0}".format(space_id) + net_data = { + "name": network_space_name, + "service": service, + "network_config": network_config, + "interfaces": interfaces, + } + + # Find existing space + net_existing = system.api.get(path=net_url) + + net_update = system.api.put( + path=net_url, + data=net_data + ) + # print("net_update: {0}".format(net_update)) + + +def get_network_space_fields(module, network_space): + fields = network_space.get_fields(from_cache=True, raw_value=True) + + field_dict = dict( + name=fields["name"], + network_space_id=fields["id"], + netmask=fields["network_config"]["netmask"], + network=fields["network_config"]["network"], + default_gateway=fields["network_config"]["default_gateway"], + interface_ids=fields["interfaces"], + service=fields["service"], + ips=fields["ips"], + properties=fields["properties"], + automatic_ip_failback=fields["automatic_ip_failback"], + mtu=fields["mtu"], + rate_limit=fields["rate_limit"], + ) + return field_dict + + +def handle_stat(module): + network_space_name = module.params["name"] + system = get_system(module) + net_space = get_net_space(module, system) + + if not net_space: + module.fail_json(msg="Network space {0} not found".format(network_space_name)) + + field_dict = get_network_space_fields(module, net_space) + result = dict( + changed=False, msg="Network space {0} stat found".format(network_space_name) + ) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + """ + If it does not already exist, create namespace. Otherwise, update namespace. + """ + network_space_name = module.params["name"] + system = get_system(module) + net_space = get_net_space(module, system) + if net_space: + changed = update_network_space(module, net_space) + msg = "Host {0} updated".format(network_space_name) + else: + changed = create_network_space(module, system) + msg = "Network space {0} created".format(network_space_name) + module.exit_json(changed=changed, msg=msg) + + +def handle_absent(module): + """ + Remove a namespace. First, may disable and remove the namespace's IPs. + """ + network_space_name = module.params["name"] + system = get_system(module) + network_space = get_net_space(module, system) + if not network_space: + changed = False + msg = "Network space {0} already absent".format(network_space_name) + else: + # Find IPs from space + ips = list(network_space.get_ips()) + + # Disable and delete IPs from space + if not module.check_mode: + for ip in ips: + addr = ip["ip_address"] + + # print("Disabling IP {0}".format(addr)) + try: + network_space.disable_ip_address(addr) + except APICommandFailed as err: + if err.error_code == "IP_ADDRESS_ALREADY_DISABLED": + pass + # print("Already disabled IP {0}".format(addr)) + else: + # print("Failed to disable IP {0}".format(addr)) + module.fail_json( + msg="Disabling of network space {0} IP {1} failed".format( + network_space_name, addr + ) + ) + + # print("Removing IP {0}".format(addr)) + try: + network_space.remove_ip_address(addr) + except Exception as err: + module.fail_json( + msg="Removal of network space {0} IP {1} failed: {2}".format( + network_space_name, addr, err + ) + ) + + # Delete space + network_space.delete() + changed = True + msg = "Network space {0} removed".format(network_space_name) + else: + changed = False + msg = "Network space {0} not altered due to checkmode".format( + network_space_name + ) + + module.exit_json(changed=changed, msg=msg) + + +def execute_state(module): + state = module.params["state"] + try: + if state == "stat": + handle_stat(module) + elif state == "present": + handle_present(module) + elif state == "absent": + handle_absent(module) + else: + module.fail_json( + msg="Internal handler error. Invalid state: {0}".format(state) + ) + finally: + system = get_system(module) + system.logout() + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + name=dict(required=True), + state=dict( + default="present", required=False, choices=["stat", "present", "absent"] + ), + service=dict( + default="replication", + required=False, + choices=["replication", "NAS_SERVICE", "ISCSI_SERVICE"], + ), + mtu=dict(default=None, required=False, type=int), + network=dict(default=None, required=False), + netmask=dict(default=None, required=False, type=int), + default_gateway=dict(default=None, required=False), + interfaces=dict(default=list(), required=False, type="list", elements="int"), + network_config=dict(default=dict(), required=False, type=dict), + ips=dict(default=list(), required=False, type="list", elements="str"), + rate_limit=dict(default=None, required=False, type=int), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib("infinisdk")) + + execute_state(module) + + +if __name__ == "__main__": + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_pool.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_pool.py new file mode 100644 index 000000000..d02657a19 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_pool.py @@ -0,0 +1,290 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_pool +version_added: '2.3.0' +short_description: Create, Delete and Modify Pools on Infinibox +description: + - This module to creates, deletes or modifies pools on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + name: + description: + - Pool Name + required: true + type: str + state: + description: + - Creates/Modifies Pool when present or removes when absent + required: false + default: present + choices: [ "stat", "present", "absent" ] + type: str + size: + description: + - Pool Physical Capacity in MB, GB or TB units. + If pool size is not set on pool creation, size will be equal to 1TB. + See examples. + required: false + type: str + vsize: + description: + - Pool Virtual Capacity in MB, GB or TB units. + If pool vsize is not set on pool creation, Virtual Capacity will be equal to Physical Capacity. + See examples. + required: false + type: str + ssd_cache: + description: + - Enable/Disable SSD Cache on Pool + required: false + default: yes + type: bool + compression: + description: + - Enable/Disable Compression on Pool + required: false + default: yes + type: bool + +notes: + - Infinibox Admin level access is required for pool modifications +extends_documentation_fragment: + - infinibox +requirements: + - capacity +''' + +EXAMPLES = r''' +- name: Make sure pool foo exists. Set pool physical capacity to 10TB + infini_pool: + name: foo + size: 10TB + vsize: 10TB + user: admin + password: secret + system: ibox001 + +- name: Disable SSD Cache on pool + infini_pool: + name: foo + ssd_cache: no + user: admin + password: secret + system: ibox001 + +- name: Disable Compression on pool + infini_pool: + name: foo + compression: no + user: admin + password: secret + system: ibox001 +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_pool, + get_system, +) + + +HAS_CAPACITY = True +try: + from capacity import KiB, Capacity +except ImportError: + HAS_CAPACITY = False + + +@api_wrapper +def create_pool(module, system): + """Create Pool""" + name = module.params['name'] + size = module.params['size'] + vsize = module.params['vsize'] + ssd_cache = module.params['ssd_cache'] + compression = module.params['compression'] + + if not module.check_mode: + if not size and not vsize: + pool = system.pools.create(name=name, physical_capacity=Capacity('1TB'), virtual_capacity=Capacity('1TB')) + elif size and not vsize: + pool = system.pools.create(name=name, physical_capacity=Capacity(size), virtual_capacity=Capacity(size)) + elif not size and vsize: + pool = system.pools.create(name=name, physical_capacity=Capacity('1TB'), virtual_capacity=Capacity(vsize)) + else: + pool = system.pools.create(name=name, physical_capacity=Capacity(size), virtual_capacity=Capacity(vsize)) + # Default value of ssd_cache is True. Disable ssd caching if False + if not ssd_cache: + pool.update_ssd_enabled(ssd_cache) + # Default value of compression is True. Disable compression if False + if not compression: + pool.update_compression_enabled(compression) + + module.exit_json(changed=True, msg='Pool created') + + +@api_wrapper +def update_pool(module, system, pool): + """Update Pool""" + changed = False + + size = module.params['size'] + vsize = module.params['vsize'] + # ssd_cache = module.params['ssd_cache'] + compression = module.params['compression'] + + # Roundup the capacity to mimic Infinibox behaviour + if size: + physical_capacity = Capacity(size).roundup(6 * 64 * KiB) + if pool.get_physical_capacity() != physical_capacity: + if not module.check_mode: + pool.update_physical_capacity(physical_capacity) + changed = True + + if vsize: + virtual_capacity = Capacity(vsize).roundup(6 * 64 * KiB) + if pool.get_virtual_capacity() != virtual_capacity: + if not module.check_mode: + pool.update_virtual_capacity(virtual_capacity) + changed = True + + # if pool.is_ssd_enabled() != ssd_cache: + # if not module.check_mode: + # pool.update_ssd_enabled(ssd_cache) + # changed = True + + if pool.is_compression_enabled() != compression: + if not module.check_mode: + pool.update_compression_enabled(compression) + changed = True + + if changed: + msg = 'Pool updated' + else: + msg = 'Pool did not require updating' + module.exit_json(changed=changed, msg=msg) + + +@api_wrapper +def delete_pool(module, pool): + """Delete Pool""" + if not module.check_mode: + pool.delete() + msg = 'Pool deleted' + module.exit_json(changed=True, msg=msg) + + +def get_sys_pool(module): + system = get_system(module) + pool = get_pool(module, system) + return (system, pool) + + +def handle_stat(module): + system, pool = get_sys_pool(module) + if not pool: + module.fail_json(msg='Pool {0} not found'.format(module.params['name'])) + fields = pool.get_fields() + # print('fields: {0}'.format(fields)) + free_physical_capacity = fields.get('free_physical_capacity', None) + pool_id = fields.get('id', None) + + result = dict( + changed=False, + free_physical_capacity=str(free_physical_capacity), + id=pool_id, + msg='Pool stat found' + ) + module.exit_json(**result) + + +def handle_present(module): + system, pool = get_sys_pool(module) + if not pool: + create_pool(module, system) + module.exit_json(changed=True, msg="Pool created") + else: + changed = update_pool(module, system, pool) + module.exit_json(changed=changed, msg="Pool updated") + + +def handle_absent(module): + system, pool = get_sys_pool(module) + if not pool: + module.exit_json(changed=False, msg="Pool already absent") + else: + delete_pool(module, pool) + module.exit_json(changed=True, msg="Pool removed") + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + name=dict(required=True), + state=dict(default='present', choices=['stat', 'present', 'absent']), + size=dict(), + vsize=dict(), + ssd_cache=dict(type='bool', default=True), + compression=dict(type='bool', default=True), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib("infinisdk")) + + if not HAS_CAPACITY: + module.fail_json(msg=missing_required_lib('capacity')) + + if module.params['size']: + try: + Capacity(module.params['size']) + except Exception: + module.fail_json(msg='size (Physical Capacity) should be defined in MB, GB, TB or PB units') + + if module.params['vsize']: + try: + Capacity(module.params['vsize']) + except Exception: + module.fail_json(msg='vsize (Virtual Capacity) should be defined in MB, GB, TB or PB units') + + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_port.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_port.py new file mode 100644 index 000000000..303127260 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_port.py @@ -0,0 +1,403 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_port +version_added: '2.9.0' +short_description: Add and Delete fiber channel and iSCSI ports to a host on Infinibox +description: + - This module adds or deletes fiber channel or iSCSI ports to hosts on + Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + host: + description: + - Host Name + required: true + state: + description: + - Creates mapping when present, removes when absent, or provides + details of a mapping when stat. + required: false + default: present + choices: [ "stat", "present", "absent" ] + type: str + wwns: + description: + - List of wwns of the host + required: false + default: [] + type: list + elements: str + iqns: + description: + - List of iqns of the host + required: false + default: [] + type: list + elements: str +extends_documentation_fragment: + - infinibox +''' + +EXAMPLES = r''' +- name: Make sure host bar is available with wwn/iqn ports + infini_host: + name: bar.example.com + state: present + wwns: + - "00:00:00:00:00:00:00" + - "11:11:11:11:11:11:11" + iqns: + - "iqn.yyyy-mm.reverse-domain:unique-string" + system: ibox01 + user: admin + password: secret +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_system, + get_host, + merge_two_dicts, +) + +try: + from infi.dtypes.wwn import WWN + from infi.dtypes.iqn import make_iscsi_name +except ImportError: + pass # Handled by HAS_INFINISDK from module_utils + + +@api_wrapper +def update_ports(module, system): + """ + Updated mapping of volume to host. If already mapped, exit_json with changed False. + """ + changed = False + + host = system.hosts.get(name=module.params["host"]) + + for wwn_port in module.params["wwns"]: + wwn = WWN(wwn_port) + if not system.hosts.get_host_by_initiator_address(wwn) == host: + if not module.check_mode: + host.add_port(wwn) + changed = True + + for iscsi_port in module.params["iqns"]: + iscsi_name = make_iscsi_name(iscsi_port) + if not system.hosts.get_host_by_initiator_address(iscsi_name) == host: + if not module.check_mode: + host.add_port(iscsi_name) + changed = True + + return changed + + +@api_wrapper +def delete_ports(module, system): + """ + Remove ports from host. + """ + changed = False + + host = system.hosts.get(name=module.params["host"]) + for wwn_port in module.params["wwns"]: + wwn = WWN(wwn_port) + if system.hosts.get_host_by_initiator_address(wwn) == host: + if not module.check_mode: + host.remove_port(wwn) + changed = True + for iscsi_port in module.params["iqns"]: + iscsi_name = make_iscsi_name(iscsi_port) + if system.hosts.get_host_by_initiator_address(iscsi_name) == host: + if not module.check_mode: + host.remove_port(iscsi_name) + changed = True + return changed + + +def get_sys_host(module): + system = get_system(module) + host = get_host(module, system) + return (system, host) + + +def edit_initiator_keys(host_initiators, include_key_list): + """ + For each host initiator, remove keys not in the include_key_list. + For FCs, add a long address. This is the address with colons inserted. + Return the edited host initiators list. + """ + trimmed_initiators = [] + for init in host_initiators: + if init["type"] == "FC" and "address" in init.keys(): + # Add address_long key to init whose value is the address with colons inserted. + address_str = str(init["address"]) + address_iter = iter(address_str) + long_address = ":".join(a + b for a, b in zip(address_iter, address_iter)) + init["address_long"] = long_address + + trimmed_item = { + key: val for key, val in init.items() if key in include_key_list + } + trimmed_initiators.append(trimmed_item) + return trimmed_initiators + + +def find_host_initiators_data(module, system, host, initiator_type): + """ + Given a host object, find its initiators that match initiator_type. + Only include desired initiator keys for each initiator. + Return the filtered and edited host initiator list. + """ + request = "initiators?page=1&page_size=1000&host_id={0}".format(host.id) + # print("\nrequest:", request, "initiator_type:", initiator_type) + get_initiators_result = system.api.get(request, check_version=False) + result_code = get_initiators_result.status_code + if result_code != 200: + msg = "get initiators REST call failed. code: {0}".format(result_code) + module.fail_json(msg=msg) + + # Only return initiators of the desired type. + host_initiators_by_type = [ + initiator + for initiator in get_initiators_result.get_result() + if initiator["type"] == initiator_type + ] + + # print("host_initiators_by_type:", host_initiators_by_type) + # print() + + # Only include certain keys in the returned initiators + if initiator_type == "FC": + include_key_list = [ + "address", + "address_long", + "host_id", + "port_key", + "targets", + "type", + ] + elif initiator_type == "ISCSI": + include_key_list = ["address", "host_id", "port_key", "targets", "type"] + else: + msg = "Cannot search for host initiator types other than FC and ISCSI" + module.fail_json(msg=msg) + host_initiators_by_type = edit_initiator_keys( + host_initiators_by_type, include_key_list + ) + + return host_initiators_by_type + + +def get_port_fields(module, system, host): + """ + Return a dict with desired fields from FC and ISCSI ports associated with the host. + """ + host_fc_initiators = find_host_initiators_data( + module, system, host, initiator_type="FC" + ) + host_iscsi_initiators = find_host_initiators_data( + module, system, host, initiator_type="ISCSI" + ) + + field_dict = dict(ports=[],) + + connectivity_lut = {0: "DISCONNECTED", 1: "DEGRADED", 2: "DEGRADED", 3: "CONNECTED"} + + ports = host.get_ports() + for port in ports: + if str(type(port)) == "<class 'infi.dtypes.wwn.WWN'>": + found_initiator = False + for initiator in host_fc_initiators: + if initiator["address"] == str(port).replace(":", ""): + found_initiator = True + # print("initiator targets:", initiator['targets']) + unique_initiator_target_ids = { + target["node_id"] for target in initiator["targets"] + } + port_dict = { + "address": str(port), + "address_long": initiator["address_long"], + "connectivity": connectivity_lut[ + len(unique_initiator_target_ids) + ], + "targets": initiator["targets"], + "type": initiator["type"], + } + + if not found_initiator: + address_str = str(port) + address_iter = iter(address_str) + long_address = ":".join( + a + b for a, b in zip(address_iter, address_iter) + ) + port_dict = { + "address": str(port), + "address_long": long_address, + "connectivity": connectivity_lut[0], + "targets": [], + "type": "FC", + } + + field_dict["ports"].append(port_dict) + + if str(type(port)) == "<class 'infi.dtypes.iqn.IQN'>": + found_initiator = False + for initiator in host_iscsi_initiators: + if initiator["address"] == str(port): + found_initiator = True + # print("initiator targets:", initiator['targets']) + unique_initiator_target_ids = { + target["node_id"] for target in initiator["targets"] + } + port_dict = { + "address": str(port), + "connectivity": connectivity_lut[ + len(unique_initiator_target_ids) + ], + "targets": initiator["targets"], + "type": initiator["type"], + } + + if not found_initiator: + port_dict = { + "address": str(port), + "connectivity": connectivity_lut[0], + "targets": [], + "type": "ISCSI", + } + + field_dict["ports"].append(port_dict) + + return field_dict + + +def handle_stat(module): + """ + Handle stat state. Fail if host is None. + Return json with status. + """ + system, host = get_sys_host(module) + + host_name = module.params["host"] + if not host: + module.fail_json(msg="Host {0} not found".format(host_name)) + + field_dict = get_port_fields(module, system, host) + result = dict(changed=False, msg="Host {0} ports found".format(host_name),) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + """ + Handle present state. Fail if host is None. + """ + system, host = get_sys_host(module) + + host_name = module.params["host"] + if not host: + module.fail_json(msg="Host {0} not found".format(host_name)) + + changed = update_ports(module, system) + if changed: + msg = "Mapping created for host {0}".format(host.get_name()) + else: + msg = "No mapping changes were required for host {0}".format(host.get_name()) + + result = dict(changed=changed, msg=msg,) + module.exit_json(**result) + + +def handle_absent(module): + """ + Handle absent state. Fail if host is None. + """ + system, host = get_sys_host(module) + if not host: + module.exit_json( + changed=False, msg="Host {0} not found".format(module.params["host"]) + ) + + changed = delete_ports(module, system) + if changed: + msg = "Mapping removed from host {0}".format(host.get_name()) + else: + msg = "No mapping changes were required. Mapping already removed from host {0}".format( + host.get_name() + ) + + result = dict(changed=changed, msg=msg,) + module.exit_json(**result) + + +def execute_state(module): + """ + Handle states. Always logout. + """ + state = module.params["state"] + try: + if state == "stat": + handle_stat(module) + elif state == "present": + handle_present(module) + elif state == "absent": + handle_absent(module) + else: + module.fail_json( + msg="Internal handler error. Invalid state: {0}".format(state) + ) + finally: + system = get_system(module) + system.logout() + + +def check_options(module): + pass + + +def main(): + """ + Gather auguments and manage mapping of vols to hosts. + """ + argument_spec = infinibox_argument_spec() + null_list = list() + argument_spec.update( + dict( + host=dict(required=True, type=str), + state=dict(default="present", choices=["stat", "present", "absent"]), + wwns=dict(type="list", elements="str", default=list()), + iqns=dict(type="list", elements="str", default=list()), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib("infinisdk")) + + check_options(module) + execute_state(module) + + +if __name__ == "__main__": + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_user.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_user.py new file mode 100644 index 000000000..01bcd0a5f --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_user.py @@ -0,0 +1,352 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_user +version_added: '2.9.0' +short_description: Create, Delete and Modify a User on Infinibox +description: + - This module creates, deletes or modifies a user on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + user_name: + description: + - The new user's Name. Once a user is created, the user_name may not be + changed from this module. It may be changed from the UI or from + infinishell. + required: true + type: str + user_email: + description: + - The new user's Email address + required: false + type: str + user_password: + description: + - The new user's password + required: false + type: str + user_role: + description: + - The user's role + required: false + choices: [ "admin", "pool_admin", "read_only" ] + type: str + user_enabled: + description: + - Specify whether to enable the user + type: bool + required: false + default: true + user_pool: + description: + - Use with role==pool_admin. Specify the new user's pool. + required: false + type: str + state: + description: + - Creates/Modifies user when present or removes when absent + required: false + default: present + choices: [ "stat", "reset_password", "present", "absent" ] + type: str + +extends_documentation_fragment: + - infinibox +''' + +EXAMPLES = r''' +- name: Create new user + infini_user: + user_name: foo_user + user_email: foo@example.com + user_password: secret2 + user_role: pool_admin + user_enabled: false + pool: foo_pool + state: present + password: secret1 + system: ibox001 +''' + +# RETURN = r''' # ''' + + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + get_system, + get_user, + get_pool, + unixMillisecondsToDate, + merge_two_dicts, +) + +try: + from infi.dtypes.iqn import make_iscsi_name +except ImportError: + pass # Handled by HAS_INFINISDK from module_utils + + +@api_wrapper +def create_user(module, system): + if not module.check_mode: + user = system.users.create(name=module.params['user_name'], + password=module.params['user_password'], + email=module.params['user_email'], + enabled=module.params['user_enabled'], + ) + # Set the user's role + user.update_role(module.params['user_role']) + if module.params['user_pool']: + if not module.params['user_role'] == 'pool_admin': + raise AssertionError("user_pool set, but role is not 'pool_admin'") + # Add the user to the pool's owners + pool = system.pools.get(name=module.params['user_pool']) + add_user_to_pool_owners(user, pool) + changed = True + return changed + + +def add_user_to_pool_owners(user, pool): + """ + Find the current list of pool owners and add user using pool.set_owners(). + set_owners() replaces the current owners with the list of new owners. So, + get owners, add user, then set owners. Further, we need to know if the + owners changed. Use sets of owners to compare. + """ + # print("add_user_to_pool_owners(): start") + changed = False + pool_fields = pool.get_fields(from_cache=True, raw_value=True) + pool_owners = pool_fields.get('owners', []) + # print('pool_owners:', pool_owners, 'pool_owners type:', type(pool_owners)) + # print('user:', user) + # print('pool:', pool) + pool_owners_set = set(pool_owners) + # print('pool_owners_set:', pool_owners_set) + new_pool_owners_set = pool_owners_set.copy() + new_pool_owners_set.add(user.id) + # print('new_pool_owners_set:', new_pool_owners_set) + if pool_owners_set != new_pool_owners_set: + pool.set_owners([user]) + changed = True + # print("changed:", changed) + # print("add_user_to_pool_owners(): end") + return changed + + +def remove_user_from_pool_owners(user, pool): + changed = False + pool_fields = pool.get_fields(from_cache=True, raw_value=True) + pool_owners = pool_fields.get('owners', []) + try: + pool_owners.remove(user) + pool.set_owners(pool_owners) + changed = True + except ValueError: + pass # User is not a pool owner + return changed + + +@api_wrapper +def update_user(module, system, user): + # print("update_user()") + if user is None: + raise AssertionError("Cannot update user {0}. User not found.".format(module.params["user_name"])) + + changed = False + fields = user.get_fields(from_cache=True, raw_value=True) + if fields.get('role') != module.params['user_role'].upper(): + user.update_field('role', module.params['user_role']) + changed = True + if fields.get('enabled') != module.params['user_enabled']: + user.update_field('enabled', module.params['user_enabled']) + changed = True + if fields.get('email') != module.params['user_email']: + user.update_field('email', module.params['user_email']) + changed = True + + if module.params['user_pool']: + try: + pool_name = module.params['user_pool'] + pool = system.pools.get(name=pool_name) + except Exception as err: + module.fail_json(msg='Cannot find pool {0}: {1}'.format(pool_name, err)) + if add_user_to_pool_owners(user, pool): + changed = True + return changed + + +@api_wrapper +def reset_user_password(module, system, user): + # print("update_user()") + if user is None: + raise AssertionError("Cannot change user {0} password. User not found.".format(module.params["user_name"])) + user.update_password(module.params['user_password']) + + +@api_wrapper +def delete_user(module, user): + if not user: + return False + + changed = True + if not module.check_mode: + # May raise APICommandFailed if mapped, etc. + user.delete() + return changed + + +def get_sys_user(module): + system = get_system(module) + user = get_user(module, system) + # print("get_sys_user(): user:", user) + return (system, user) + + +def get_user_fields(user): + pools = user.get_owned_pools() + pool_names = [pool.get_field('name') for pool in pools] + + fields = user.get_fields(from_cache=True, raw_value=True) + field_dict = dict( + id=user.id, + enabled=fields.get('enabled', None), + role=fields.get('role', None), + email=fields.get('email', None), + pools=pool_names, + ) + return field_dict + + +def handle_stat(module): + system, user = get_sys_user(module) + user_name = module.params["user_name"] + if not user: + module.fail_json(msg='User {0} not found'.format(user_name)) + field_dict = get_user_fields(user) + result = dict( + changed=False, + msg='User stat found' + ) + result = merge_two_dicts(result, field_dict) + module.exit_json(**result) + + +def handle_present(module): + system, user = get_sys_user(module) + user_name = module.params["user_name"] + if not user: + changed = create_user(module, system) + msg = 'User {0} created'.format(user_name) + else: + changed = update_user(module, system, user) + if changed: + msg = 'User {0} updated'.format(user_name) + else: + msg = 'User {0} update required no changes'.format(user_name) + module.exit_json(changed=changed, msg=msg) + + +def handle_absent(module): + system, user = get_sys_user(module) + user_name = module.params["user_name"] + if not user: + changed = False + msg = "User {0} already absent".format(user_name) + else: + changed = delete_user(module, user) + msg = "User {0} removed".format(user_name) + module.exit_json(changed=changed, msg=msg) + + +def handle_reset_password(module): + system, user = get_sys_user(module) + user_name = module.params["user_name"] + if not user: + msg = 'Cannot change password. User {0} not found'.format(user_name) + module.fail_json(msg=msg) + else: + reset_user_password(module, system, user) + msg = 'User {0} password changed'.format(user_name) + module.exit_json(changed=True, msg=msg) + + +def execute_state(module): + state = module.params['state'] + try: + if state == 'stat': + handle_stat(module) + elif state == 'present': + handle_present(module) + elif state == 'absent': + handle_absent(module) + elif state == 'reset_password': + handle_reset_password(module) + else: + module.fail_json(msg='Internal handler error. Invalid state: {0}'.format(state)) + finally: + system = get_system(module) + system.logout() + + +def check_options(module): + state = module.params['state'] + user_role = module.params['user_role'] + user_pool = module.params['user_pool'] + if state == 'present': + if user_role == 'pool_admin' and not user_pool: + module.fail_json(msg='user_role "pool_admin" requires a user_pool to be provided') + if user_role != 'pool_admin' and user_pool: + module.fail_json(msg='Only user_role "pool_admin" should have a user_pool provided') + + valid_keys = ['user_email', 'user_password', 'user_role', 'user_enabled'] + for valid_key in valid_keys: + # Check required keys provided + try: + not_used = module.params[valid_key] + except KeyError: + msg = 'For state "present", options {0} are required'.format(", ".join(valid_keys)) + module.fail_json(msg=msg) + elif state == 'reset_password': + if not module.params['user_password']: + msg = 'For state "reset_password", user_password is required' + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + user_name=dict(required=True), + user_email=dict(required=False), + user_password=dict(required=False, no_log=True), + user_role=dict(required=False, choices=['admin', 'pool_admin', 'read_only']), + user_enabled=dict(required=False, type='bool', default=True), + user_pool=dict(required=False), + state=dict(default='present', choices=['stat', 'reset_password', 'present', 'absent']), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib('infinisdk')) + + check_options(module) + execute_state(module) + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/infinidat/infinibox/plugins/modules/infini_vol.py b/ansible_collections/infinidat/infinibox/plugins/modules/infini_vol.py new file mode 100644 index 000000000..0c4a579bc --- /dev/null +++ b/ansible_collections/infinidat/infinibox/plugins/modules/infini_vol.py @@ -0,0 +1,619 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2022, Infinidat <info@infinidat.com> +# 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 = r''' +--- +module: infini_vol +version_added: '2.3.0' +short_description: Create, Delete or Modify volumes on Infinibox +description: + - This module creates, deletes or modifies a volume on Infinibox. +author: David Ohlemacher (@ohlemacher) +options: + name: + description: + - Volume Name + required: true + parent_volume_name: + description: + - Specify a volume name. This is the volume parent for creating a snapshot. Required if volume_type is snapshot. + required: false + pool: + description: + - Pool that master volume will reside within. Required for creating a master volume, but not a snapshot. + required: false + size: + description: + - Volume size in MB, GB or TB units. Required for creating a master volume, but not a snapshot + required: false + snapshot_lock_expires_at: + description: + - This will cause a snapshot to be locked at the specified date-time. + Uses python's datetime format YYYY-mm-dd HH:MM:SS.ffffff, e.g. 2020-02-13 16:21:59.699700 + required: false + snapshot_lock_only: + description: + - This will lock an existing snapshot but will suppress refreshing the snapshot. + type: bool + required: false + default: false + state: + description: + - Creates/Modifies master volume or snapshot when present or removes when absent. + required: false + default: present + choices: [ "stat", "present", "absent" ] + thin_provision: + description: + - Whether the master volume should be thin or thick provisioned. + type: bool + required: false + default: true + write_protected: + description: + - Specifies if the volume should be write protected. Default will be True for snapshots, False for regular volumes. + required: false + default: "Default" + choices: ["Default", "True", "False"] + volume_type: + description: + - Specifies the volume type, regular volume or snapshot. + required: false + default: master + choices: [ "master", "snapshot" ] + restore_volume_from_snapshot: + description: + - Specify true to restore a volume (parent_volume_name) from an existing snapshot specified by the name field. + - State must be set to present and volume_type must be 'snapshot'. + required: false + default: false +extends_documentation_fragment: + - infinibox +requirements: + - capacity +''' + +EXAMPLES = r''' +- name: Create new volume named foo under pool named bar + infini_vol: + name: foo + # volume_type: master # Default + size: 1TB + thin_provision: yes + pool: bar + state: present + user: admin + password: secret + system: ibox001 +- name: Create snapshot named foo_snap from volume named foo + infini_vol: + name: foo_snap + volume_type: snapshot + parent_volume_name: foo + state: present + user: admin + password: secret + system: ibox001 +- name: Stat snapshot, also a volume, named foo_snap + infini_vol: + name: foo_snap + state: present + user: admin + password: secret + system: ibox001 +- name: Remove snapshot, also a volume, named foo_snap + infini_vol: + name: foo_snap + state: absent + user: admin + password: secret + system: ibox001 +''' + +# RETURN = r''' # ''' + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib + +import traceback + +from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import ( + HAS_INFINISDK, + api_wrapper, + infinibox_argument_spec, + ObjectNotFound, + get_pool, + get_system, + get_volume, + get_vol_sn, +) + + +HAS_CAPACITY = True +try: + from capacity import KiB, Capacity +except ImportError: + HAS_CAPACITY = False + +HAS_ARROW = True +try: + import arrow +except ImportError: + HAS_ARROW = False + +except Exception: + HAS_INFINISDK = False + + +@api_wrapper +def create_volume(module, system): + """Create Volume""" + changed = False + if not module.check_mode: + if module.params["thin_provision"]: + prov_type = "THIN" + else: + prov_type = "THICK" + pool = get_pool(module, system) + volume = system.volumes.create( + name=module.params["name"], provtype=prov_type, pool=pool + ) + + if module.params["size"]: + size = Capacity(module.params["size"]).roundup(64 * KiB) + volume.update_size(size) + if module.params["write_protected"] is not None: + is_write_prot = volume.is_write_protected() + desired_is_write_prot = module.params["write_protected"] + if is_write_prot != desired_is_write_prot: + volume.update_field("write_protected", desired_is_write_prot) + changed = True + return changed + + +@api_wrapper +def find_vol_id(module, system, vol_name): + """ + Find the ID of this vol + """ + vol_url = "volumes?name={0}&fields=id".format(vol_name) + vol = system.api.get(path=vol_url) + + result = vol.get_json()["result"] + if len(result) != 1: + module.fail_json("Cannot find a volume with name '{0}'".format(vol_name)) + + vol_id = result[0]["id"] + # print("Volume {} has ID {}".format(vol_name, vol_id)) + return vol_id + + +@api_wrapper +def restore_volume_from_snapshot(module, system): + """Use snapshot to restore a volume""" + changed = False + is_restoring = module.params["restore_volume_from_snapshot"] + volume_type = module.params["volume_type"] + snap_name = module.params["name"] + snap_id = find_vol_id(module, system, snap_name) + parent_volume_name = module.params["parent_volume_name"] + parent_volume_id = find_vol_id(module, system, parent_volume_name) + + # Check params + if not is_restoring: + raise AssertionError("A programming error occurred. is_restoring is not True") + if volume_type != "snapshot": + module.fail_json( + msg="Cannot restore a parent volume from snapshot unless the volume " + "type is 'snapshot'" + ) + if not parent_volume_name: + module.fail_json( + msg="Cannot restore a parent volume from snapshot unless the parent " + "volume name is specified" + ) + + if not module.check_mode: + restore_url = "volumes/{0}/restore?approved=true".format(parent_volume_id) + restore_data = { + "source_id": snap_id, + } + restore = system.api.post(path=restore_url, data=restore_data) + changed = True + return changed + + +@api_wrapper +def update_volume(module, volume): + """Update Volume""" + changed = False + if module.params["size"]: + size = Capacity(module.params["size"]).roundup(64 * KiB) + if volume.get_size() != size: + if not module.check_mode: + volume.update_size(size) + changed = True + if module.params["thin_provision"] is not None: + type = str(volume.get_provisioning()) + if type == "THICK" and module.params["thin_provision"]: + if not module.check_mode: + volume.update_provisioning("THIN") + changed = True + if type == "THIN" and not module.params["thin_provision"]: + if not module.check_mode: + volume.update_provisioning("THICK") + changed = True + if module.params["write_protected"] is not None: + is_write_prot = volume.is_write_protected() + desired_is_write_prot = module.params["write_protected"] + if is_write_prot != desired_is_write_prot: + volume.update_field("write_protected", desired_is_write_prot) + + return changed + + +@api_wrapper +def delete_volume(module, volume): + """ Delete Volume. Volume could be a snapshot.""" + if not module.check_mode: + volume.delete() + changed = True + return True + + +@api_wrapper +def create_snapshot(module, system): + """Create Snapshot from parent volume""" + snapshot_name = module.params["name"] + parent_volume_name = module.params["parent_volume_name"] + try: + parent_volume = system.volumes.get(name=parent_volume_name) + except ObjectNotFound as err: + msg = "Cannot create snapshot {0}. Parent volume {1} not found".format( + snapshot_name, parent_volume_name + ) + module.fail_json(msg=msg) + if not parent_volume: + msg = "Cannot find new snapshot's parent volume named {0}".format( + parent_volume_name + ) + module.fail_json(msg=msg) + if not module.check_mode: + if module.params["snapshot_lock_only"]: + msg = "Snapshot does not exist. Cannot comply with 'snapshot_lock_only: true'." + module.fail_json(msg=msg) + check_snapshot_lock_options(module) + snapshot = parent_volume.create_snapshot(name=snapshot_name) + + if module.params["write_protected"] is not None: + is_write_prot = snapshot.is_write_protected() + desired_is_write_prot = module.params["write_protected"] + if is_write_prot != desired_is_write_prot: + snapshot.update_field("write_protected", desired_is_write_prot) + + manage_snapshot_locks(module, snapshot) + changed = True + return changed + + +@api_wrapper +def update_snapshot(module, snapshot): + """ + Update/refresh snapshot. May also lock it. + """ + refresh_changed = False + if not module.params["snapshot_lock_only"]: + snap_is_locked = snapshot.get_lock_state() == "LOCKED" + if not snap_is_locked: + if not module.check_mode: + snapshot.refresh_snapshot() + refresh_changed = True + else: + msg = "Snapshot is locked and may not be refreshed" + module.fail_json(msg=msg) + + check_snapshot_lock_options(module) + lock_changed = manage_snapshot_locks(module, snapshot) + + if not module.check_mode: + if module.params["write_protected"] is not None: + is_write_prot = snapshot.is_write_protected() + desired_is_write_prot = module.params["write_protected"] + if is_write_prot != desired_is_write_prot: + snapshot.update_field("write_protected", desired_is_write_prot) + + return refresh_changed or lock_changed + + +def get_sys_pool_vol_parname(module): + system = get_system(module) + pool = get_pool(module, system) + if module.params["name"]: + volume = get_volume(module, system) + else: + volume = get_vol_sn(module, system) + parname = module.params["parent_volume_name"] + return (system, pool, volume, parname) + + +def check_snapshot_lock_options(module): + """ + Check if specified options are feasible for a snapshot. + + Prevent very long lock times. + max_delta_minutes limits locks to 30 days (43200 minutes). + + This functionality is broken out from manage_snapshot_locks() to allow + it to be called by create_snapshot() before the snapshot is actually + created. + """ + snapshot_lock_expires_at = module.params["snapshot_lock_expires_at"] + + if snapshot_lock_expires_at: # Then user has specified wish to lock snap + lock_expires_at = arrow.get(snapshot_lock_expires_at) + + # Check for lock in the past + now = arrow.utcnow() + if lock_expires_at <= now: + msg = "Cannot lock snapshot with a snapshot_lock_expires_at " + msg += "of '{0}' from the past".format(snapshot_lock_expires_at) + module.fail_json(msg=msg) + + # Check for lock later than max lock, i.e. too far in future. + max_delta_minutes = 43200 # 30 days in minutes + max_lock_expires_at = now.shift(minutes=max_delta_minutes) + if lock_expires_at >= max_lock_expires_at: + msg = "snapshot_lock_expires_at exceeds {0} days in the future".format( + max_delta_minutes // 24 // 60 + ) + module.fail_json(msg=msg) + + +def manage_snapshot_locks(module, snapshot): + """ + Manage the locking of a snapshot. Check for bad lock times. + See check_snapshot_lock_options() which has additional checks. + """ + name = module.params["name"] + snapshot_lock_expires_at = module.params["snapshot_lock_expires_at"] + snap_is_locked = snapshot.get_lock_state() == "LOCKED" + current_lock_expires_at = snapshot.get_lock_expires_at() + changed = False + + check_snapshot_lock_options(module) + + if snapshot_lock_expires_at: # Then user has specified wish to lock snap + lock_expires_at = arrow.get(snapshot_lock_expires_at) + if snap_is_locked and lock_expires_at < current_lock_expires_at: + # Lock earlier than current lock + msg = "snapshot_lock_expires_at '{0}' preceeds the current lock time of '{1}'".format( + lock_expires_at, current_lock_expires_at + ) + module.fail_json(msg=msg) + elif snap_is_locked and lock_expires_at == current_lock_expires_at: + # Lock already set to correct time + pass + else: + # Set lock + if not module.check_mode: + snapshot.update_lock_expires_at(lock_expires_at) + changed = True + return changed + + +def handle_stat(module): + system, pool, volume, parname = get_sys_pool_vol_parname(module) + if not volume: + msg = "Volume {0} not found. Cannot stat.".format(module.params["name"]) + module.fail_json(msg=msg) + fields = volume.get_fields() # from_cache=True, raw_value=True) + created_at = str(fields.get("created_at", None)) + has_children = fields.get("has_children", None) + lock_expires_at = str(volume.get_lock_expires_at()) + lock_state = volume.get_lock_state() + mapped = str(fields.get("mapped", None)) + name = fields.get("name", None) + parent_id = fields.get("parent_id", None) + provisioning = fields.get("provisioning", None) + serial = str(volume.get_serial()) + size = str(volume.get_size()) + updated_at = str(fields.get("updated_at", None)) + used = str(fields.get("used_size", None)) + volume_id = fields.get("id", None) + volume_type = fields.get("type", None) + write_protected = fields.get("write_protected", None) + if volume_type == "SNAPSHOT": + msg = "Snapshot stat found" + else: + msg = "Volume stat found" + + result = dict( + changed=False, + name=name, + created_at=created_at, + has_children=has_children, + lock_expires_at=lock_expires_at, + lock_state=lock_state, + mapped=mapped, + msg=msg, + parent_id=parent_id, + provisioning=provisioning, + serial=serial, + size=size, + updated_at=updated_at, + used=used, + volume_id=volume_id, + volume_type=volume_type, + write_protected=write_protected, + ) + module.exit_json(**result) + + +def handle_present(module): + system, pool, volume, parname = get_sys_pool_vol_parname(module) + volume_type = module.params["volume_type"] + is_restoring = module.params["restore_volume_from_snapshot"] + if volume_type == "master": + if not volume: + changed = create_volume(module, system) + module.exit_json(changed=changed, msg="Volume created") + else: + changed = update_volume(module, volume) + module.exit_json(changed=changed, msg="Volume updated") + elif volume_type == "snapshot": + snapshot = volume + if is_restoring: + # Restore volume from snapshot + changed = restore_volume_from_snapshot(module, system) + module.exit_json(changed=changed, msg="Volume restored from snapshot") + else: + if not snapshot: + changed = create_snapshot(module, system) + module.exit_json(changed=changed, msg="Snapshot created") + else: + changed = update_snapshot(module, snapshot) + module.exit_json(changed=changed, msg="Snapshot updated") + else: + module.fail_json(msg="A programming error has occurred") + + +def handle_absent(module): + system, pool, volume, parname = get_sys_pool_vol_parname(module) + volume_type = module.params["volume_type"] + + if volume and volume.get_lock_state() == "LOCKED": + msg = "Cannot delete snapshot. Locked." + module.fail_json(msg=msg) + + if volume_type == "master": + if not volume: + module.exit_json(changed=False, msg="Volume already absent") + else: + changed = delete_volume(module, volume) + module.exit_json(changed=changed, msg="Volume removed") + elif volume_type == "snapshot": + if not volume: + module.exit_json(changed=False, msg="Snapshot already absent") + else: + snapshot = volume + changed = delete_volume(module, snapshot) + module.exit_json(changed=changed, msg="Snapshot removed") + else: + module.fail_json(msg="A programming error has occured") + + +def execute_state(module): + # Handle different write_protected defaults depending on volume_type. + if module.params["volume_type"] == "snapshot": + if module.params["write_protected"] in ["True", "true", "Default"]: + module.params["write_protected"] = True + else: + module.params["write_protected"] = False + elif module.params["volume_type"] == "master": + if module.params["write_protected"] in ["False", "false", "Default"]: + module.params["write_protected"] = False + else: + module.params["write_protected"] = True + else: + msg = f"An error has occurred handling volume_type '{module.params['volume_type']}' or write_protected '{module.params['write_protected']}' values" + module.fail_json(msg=msg) + + state = module.params["state"] + try: + if state == "stat": + handle_stat(module) + elif state == "present": + handle_present(module) + elif state == "absent": + handle_absent(module) + else: + module.fail_json( + msg="Internal handler error. Invalid state: {0}".format(state) + ) + finally: + system = get_system(module) + system.logout() + + +def check_options(module): + """Verify module options are sane""" + state = module.params["state"] + size = module.params["size"] + pool = module.params["pool"] + volume_type = module.params["volume_type"] + parent_volume_name = module.params["parent_volume_name"] + + if state == "present": + if volume_type == "master": + if state == "present": + if parent_volume_name: + msg = "parent_volume_name should not be specified " + msg += "if volume_type is 'volume'. Snapshots only." + module.fail_json(msg=msg) + if not size: + msg = "Size is required to create a volume" + module.fail_json(msg=msg) + elif volume_type == "snapshot": + if size or pool: + msg = "Neither pool nor size should not be specified " + msg += "for volume_type snapshot" + module.fail_json(msg=msg) + if state == "present": + if not parent_volume_name: + msg = "For state 'present' and volume_type 'snapshot', " + msg += "parent_volume_name is required" + module.fail_json(msg=msg) + else: + msg = "A programming error has occurred" + module.fail_json(msg=msg) + + +def main(): + argument_spec = infinibox_argument_spec() + argument_spec.update( + dict( + name=dict(required=False), + parent_volume_name=dict(default=None, required=False, type=str), + pool=dict(required=False), + size=dict(), + serial=dict(), + snapshot_lock_expires_at=dict(), + snapshot_lock_only=dict(type="bool", default=False), + state=dict(default="present", choices=["stat", "present", "absent"]), + thin_provision=dict(type="bool", default=True), + write_protected=dict( + default="Default", choices=["Default", "True", "False"] + ), + volume_type=dict(default="master", choices=["master", "snapshot"]), + restore_volume_from_snapshot=dict(default=False, type=bool), + ) + ) + + module = AnsibleModule(argument_spec, supports_check_mode=True) + + if not HAS_INFINISDK: + module.fail_json(msg=missing_required_lib("infinisdk")) + + if not HAS_ARROW: + module.fail_json(msg=missing_required_lib("arrow")) + + if module.params["size"]: + try: + Capacity(module.params["size"]) + except Exception: + module.fail_json( + msg="size (Physical Capacity) should be defined in MB, GB, TB or PB units" + ) + + check_options(module) + execute_state(module) + + +if __name__ == "__main__": + main() diff --git a/ansible_collections/infinidat/infinibox/requirements-dev.txt b/ansible_collections/infinidat/infinibox/requirements-dev.txt new file mode 100644 index 000000000..c77aeebbf --- /dev/null +++ b/ansible_collections/infinidat/infinibox/requirements-dev.txt @@ -0,0 +1,6 @@ +ansible +ansible-core +pycodestyle +pylint +pytest +PyYAML diff --git a/ansible_collections/infinidat/infinibox/requirements.txt b/ansible_collections/infinidat/infinibox/requirements.txt new file mode 100644 index 000000000..bc5c04029 --- /dev/null +++ b/ansible_collections/infinidat/infinibox/requirements.txt @@ -0,0 +1,67 @@ +api-object-schema +appdirs +arrow +asn1crypto +astroid +atomicwrites +attrs +black +capacity +certifi +cffi +chardet +charset-normalizer +click +colorama +confetti +cryptography +dataclasses +flux +gossip +idna +importlib-metadata +infi.dtypes.iqn +infi.dtypes.wwn +infinisdk +iniconfig +isort +Jinja2 +lazy-object-proxy +Logbook +MarkupSafe +mccabe +mitba +more-itertools +munch +mypy-extensions +packaging +pact +pathspec +platformdirs +pluggy +py +pycparser +pyparsing +python-dateutil +regex +requests +resolvelib +ruamel.yaml +ruamel.yaml.clib +sentinels +# sh +six +storage-interfaces +toml +tomli +typed-ast +typing_extensions +urllib3 +URLObject +vintage +voluptuous +waiting +wcwidth +wheel +wrapt +zipp diff --git a/ansible_collections/infinidat/infinibox/tests/hacking/infini_vol_present_example.json b/ansible_collections/infinidat/infinibox/tests/hacking/infini_vol_present_example.json new file mode 100644 index 000000000..72e16537b --- /dev/null +++ b/ansible_collections/infinidat/infinibox/tests/hacking/infini_vol_present_example.json @@ -0,0 +1,13 @@ +{ + "ANSIBLE_MODULE_ARGS": { + "name": "app_snap", + "parent_volume_name": "app_vol", + "state": "present", + "volume_type": "snapshot", + "restore_volume_from_snapshot": true, + + "system": "ibox1521.lab.wt.us.infinidat.com", + "user": "psus-gitlab-cicd", + "password": "redacted" + } +} diff --git a/ansible_collections/infinidat/infinibox/tests/sanity/ignore-2.10.txt b/ansible_collections/infinidat/infinibox/tests/sanity/ignore-2.10.txt new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/ansible_collections/infinidat/infinibox/tests/sanity/ignore-2.10.txt |