diff --git a/README.md b/README.md
index 5ad2025..cd9c886 100644
--- a/README.md
+++ b/README.md
@@ -45,7 +45,7 @@ What you should know
Requirements
------------
-This role works on CentOS 6 and 7. RHEL was not tested but should work without problem. If you need support for other distribution, I can help. Post an issue.
+This role works on CentOS 6/7/8. RHEL was not tested but it should also work.
The postgresql binaries on your primary server should be installed from the official repository:
@@ -79,9 +79,9 @@ Example Playbook
The usage is relatively simple - install minimal CentOS-es, set the variables and run the role.
-Two settings are required:
+Two ansible settings are required:
- `gather_facts=True` - we need to know the IP addresses of cluster nodes
-- `any_errors_fatal=True` - it ensures that error on any node will result in stopping the whole ansible run. Because it doesn't make sense to continue when you lose some of your cluster nodes during transit.
+- `any_errors_fatal=True` - it ensures that error on any node will result in stopping the whole ansible run. Because it doesn't make sense to continue when you lose some of your cluster nodes during the process.
```
- name: install PG HA
@@ -89,6 +89,7 @@ Two settings are required:
gather_facts: True
any_errors_fatal: True
vars:
+ postgres_ha_pg_version: 14
postgres_ha_cluster_master_host: db1
postgres_ha_cluster_vip: 10.10.10.10
postgres_ha_pg_repl_pass: MySuperSecretDBPass
@@ -104,6 +105,8 @@ Two settings are required:
Cleanup after failure
---------------------
+The role can fail. The clustering process is complicated beast and sometimes behaves unexpectedly. Re-running the role often helps.
+
If the role fails repeatedly and you want to run it fresh as if it was the first time, you need to clean up some things.
Please note that default resource names are used here. If you change them using variables, you need to change it also in these commands.
@@ -111,32 +114,33 @@ Please note that default resource names are used here. If you change them using
```
pcs resource delete pg-vip
pcs resource delete postgres
-#pcs resource delete postgres-ha # probably not needed
-#pcs resource cleanup postgres # probably not needed
+pcs resource cleanup postgres # sometimes needed
+#pcs resource delete postgres-ha # probably not needed
# Make sure no (related) cluster resources are defined.
```
- RUN ON ALL SLAVE NODES:
```
-systemctl stop postgresql-9.6
+systemctl stop postgresql-14
# Make sure no postgres db is running.
-systemctl status postgresql-9.6
+systemctl status postgresql-14
ps aux | grep postgres
-rm -rf /var/lib/pgsql/9.6/data
-rm -f /var/lib/pgsql/9.6/recovery.conf.pgcluster.pcmk
-rm -f /var/lib/pgsql/9.6/.*_constraints_processed # name generated from postgres_ha_cluster_pg_res_name
+rm -rf /var/lib/pgsql/14/data
+rm -f /var/lib/pgsql/14/.*_constraints_processed # name generated from postgres_ha_cluster_pg_res_name
+rm -f /var/lib/pgsql/14/recovery.conf.pgcluster.pcmk # only pg < 12
```
- RUN ONLY ON MASTER NODE:
```
-systemctl stop postgresql-9.6
-rm -f /var/lib/pgsql/9.6/recovery.conf.pgcluster.pcmk
-rm -f /var/lib/pgsql/9.6/.*_constraints_processed
-rm -f /var/lib/pgsql/9.6/data/recovery.conf
-rm -f /var/lib/pgsql/9.6/data/.synchronized
+systemctl stop postgresql-14
+rm -f /var/lib/pgsql/14/.*_constraints_processed
+rm -f /var/lib/pgsql/14/data/.synchronized
+rm -f /var/lib/pgsql/14/data/standby.signal # only pg >= 12
+rm -f /var/lib/pgsql/14/data/recovery.conf # only pg < 12
+rm -f /var/lib/pgsql/14/recovery.conf.pgcluster.pcmk # only pg < 12
# Make sure no postgres db is running.
ps aux | grep postgres
-systemctl start postgresql-9.6
-systemctl status postgresql-9.6
+systemctl start postgresql-14
+systemctl status postgresql-14
# Check postgres db functionality.
```
- START AGAIN
diff --git a/defaults/main.yml b/defaults/main.yml
index ffe1d1d..b4f4e71 100644
--- a/defaults/main.yml
+++ b/defaults/main.yml
@@ -19,9 +19,9 @@ postgres_ha_cluster_ha_password: 'fropFav7epAbOch2' # password for joinin
postgres_ha_cluster_ha_password_hash: '$6$MHAki4YS$Nk7O3FEC2G.INznoSUj4ByFgdwFJ8mcI9.Ks3XAoLLe9f9GB36G8hZe9o8ygDySJwvnLVCn0LGPzcOapK42/A/' # fropFav7epAbOch2
# postgres config
-postgres_ha_pg_version: 9.6
+postgres_ha_pg_version: 14
postgres_ha_import_repo: true # Enable download of postgresql repo before install
-postgres_ha_repo_url: 'https://download.postgresql.org/pub/repos/yum/{{ postgres_ha_pg_version }}/redhat/rhel-7-x86_64/{{ pg_pkg_name }}'
+postgres_ha_repo_url: 'https://download.postgresql.org/pub/repos/yum/reporpms/EL-{{ ansible_distribution_major_version }}-x86_64/pgdg-redhat-repo-latest.noarch.rpm'
postgres_ha_pg_systemd_svcname: "postgresql-{{ postgres_ha_pg_version }}" # the name of the original posgres DB resource in systemd
postgres_ha_pg_data: "/var/lib/pgsql/{{ postgres_ha_pg_version }}/data" # where can I find PG datadir?
postgres_ha_pg_bindir: "/usr/pgsql-{{ postgres_ha_pg_version }}/bin" # where are the PG binaries?
@@ -34,10 +34,14 @@ postgres_ha_postgresql_conf_vars: # When altering this
hot_standby: "on"
wal_log_hints: "on"
+postgres_ha_postgresql_conf_vars_12: # Additional conf vars for pg12+
+ primary_conninfo: "'port={{ postgres_ha_pg_port }} host={{ postgres_ha_cluster_vip }} user={{ postgres_ha_pg_repl_user }} application_name={{ inventory_hostname }}'"
+ recovery_target_timeline: "'latest'"
+
postgres_ha_maint_scripts_path: /var/lib/pgsql/pg-maint # location where to create user scripts for database administration
# PAF vars
-postgres_ha_paf_version: 2.2.1
+postgres_ha_paf_version: 2.3.0
postgres_ha_paf_geo_patch: False # Apply a patch to PAF to better handle network splits in geographically split clusters.
# This patch is from creator of this ansible role and is not official.
# It allows having a postgresql master-slave cluster without the need of fencing configured
diff --git a/files/resource-agents-paf-2.3.0-1.noarch.rpm b/files/resource-agents-paf-2.3.0-1.noarch.rpm
new file mode 100644
index 0000000..1ff366b
Binary files /dev/null and b/files/resource-agents-paf-2.3.0-1.noarch.rpm differ
diff --git a/library/LICENSE b/library/LICENSE
new file mode 100644
index 0000000..50e969b
--- /dev/null
+++ b/library/LICENSE
@@ -0,0 +1,8 @@
+These modules are licensed under the terms of the General Public License (GPL) Version 3,
+or alternatively under the terms of the Apache License Version 2.0.
+
+Feel free to from above licenses the one that suits best your project.
+
+The terms of each license can be found in the following files:
+GPLv3: LICENSE-GPLv3.txt
+Apache License 2.0: LICENSE-APACHE2.txt
diff --git a/library/LICENSE-APACHE2.txt b/library/LICENSE-APACHE2.txt
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/library/LICENSE-APACHE2.txt
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/library/LICENSE-GPLv3.txt b/library/LICENSE-GPLv3.txt
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/library/LICENSE-GPLv3.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ 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.
+
+
+ Copyright (C)
+
+ 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 .
+
+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:
+
+ Copyright (C)
+ 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
+.
+
+ 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
+.
diff --git a/library/README.TXT b/library/README.TXT
new file mode 100644
index 0000000..2948bcc
--- /dev/null
+++ b/library/README.TXT
@@ -0,0 +1 @@
+PCS modules downloaded from https://github.com/OndrejHome/ansible.pcs-modules-2.git
diff --git a/library/detect_pacemaker_cluster.py b/library/detect_pacemaker_cluster.py
new file mode 100644
index 0000000..c5f0237
--- /dev/null
+++ b/library/detect_pacemaker_cluster.py
@@ -0,0 +1,74 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+module: detect_pacemaker_cluster
+author: "Ondrej Famera (@ondrejHome)"
+short_description: detect facts about installed pacemaker cluster
+description:
+ - Module for collecting various information about pacemaker cluster
+version_added: "2.4"
+notes:
+ - Tested on CentOS 7.5
+ - works only with pacemaker clusters that uses /etc/corosync/corosync.conf
+requirements: [ ]
+'''
+
+EXAMPLES = '''
+- detect_pacemaker_cluster
+
+'''
+
+import re
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(),
+ supports_check_mode=True
+ )
+
+ result = {}
+
+ try:
+ corosync_conf = open('/etc/corosync/corosync.conf', 'r')
+ nodes = re.compile(r"node\s*\{([^}]+)\}", re.M + re.S)
+ nodes_list = nodes.findall(corosync_conf.read())
+ node_list_set = set()
+ if len(nodes_list) > 0:
+ n_name = re.compile(r"ring0_addr\s*:\s*([\w.-]+)\s*", re.M)
+ for node in nodes_list:
+ n_name2 = None
+ n_name2 = n_name.search(node)
+ if n_name2:
+ node_name = n_name2.group(1)
+ node_list_set.add(node_name.rstrip())
+
+ result['ansible_facts'] = {}
+ result['ansible_facts']['pacemaker_detected_cluster_nodes'] = node_list_set
+ result['ansible_facts']['pacemaker_cluster_present'] = True
+ except IOError as e:
+ result['ansible_facts'] = {}
+ result['ansible_facts']['pacemaker_cluster_present'] = False
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_auth.py b/library/pcs_auth.py
new file mode 100644
index 0000000..d1dfc42
--- /dev/null
+++ b/library/pcs_auth.py
@@ -0,0 +1,178 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_auth
+short_description: Module for interacting with 'pcs auth'
+description:
+ - module for authenticating nodes in pacemaker cluster using 'pcs auth' for RHEL/CentOS.
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' authenticates the node while 'absent' will remove the node authentification"
+ - "node from which this is run is (de)authenticated agains the node specified in 'node_name'"
+ required: false
+ default: present
+ choices: [ 'present', 'absent' ]
+ type: str
+ node_name:
+ description:
+ - hostname of node for authentication
+ required: true
+ type: str
+ username:
+ description:
+ - "username of 'cluster user' for cluster authentication"
+ required: false
+ default: 'hacluster'
+ type: str
+ password:
+ description:
+ - "password of 'cluster user' for cluster authentication"
+ required: false
+ type: str
+notes:
+ - This module is (de)authenticating nodes only 1-way == authenticating node 1 agains
+ node 2 doesn't mean that node 2 is authenticated agains node 1!
+ - Tested on CentOS 6.8, 7.3
+ - Tested on Red Hat Enterprise Linux 7.3, 7.4, 7.6
+ - Experimental support for Red Hat Enterprise Linux 8.0 Beta and pcs 0.10
+'''
+
+EXAMPLES = '''
+- name: Authorize node 'n1' with default user 'hacluster' and password 'testtest'
+ pcs_auth:
+ node_name: 'n1'
+ password: 'testtest'
+
+- name: authorize all nodes in ansible play to each other
+ pcs_auth:
+ node_name: "{{ hostvars[item]['ansible_hostname'] }}"
+ password: 'testtest'
+ with_items: "{{ play_hosts }}"
+
+- name: de-authorize all nodes from each other in ansible play
+ pcs_auth:
+ node_name: "{{ hostvars[item]['ansible_hostname'] }}"
+ state: 'absent'
+ with_items: "{{ play_hosts }}"
+
+'''
+
+import os.path
+import json
+from distutils.spawn import find_executable
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ node_name=dict(required=True),
+ username=dict(required=False, default="hacluster"),
+ password=dict(required=False, no_log=True)
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ node_name = module.params['node_name']
+
+ if state == 'present' and not module.params['password']:
+ module.fail_json(msg="Missing password parameter needed for authorizing the node")
+
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ # get the pcs major.minor version
+ rc, out, err = module.run_command('pcs --version')
+ if rc == 0:
+ pcs_version = out.split('.')[0] + '.' + out.split('.')[1]
+ else:
+ module.fail_json(msg="pcs --version exited with non-zero exit code (" + rc + "): " + out + err)
+
+ if os.path.isfile('/var/lib/pcsd/tokens') and pcs_version == '0.9':
+ tokens_file = open('/var/lib/pcsd/tokens', 'r+')
+ # load JSON tokens
+ tokens_data = json.load(tokens_file)
+ result['tokens_data'] = tokens_data['tokens']
+ if os.path.isfile('/var/lib/pcsd/known-hosts') and pcs_version == '0.10':
+ tokens_file = open('/var/lib/pcsd/known-hosts', 'r+')
+ # load JSON tokens
+ tokens_data = json.load(tokens_file)
+ result['tokens_data'] = tokens_data['known_hosts']
+
+ rc, out, err = module.run_command('pcs cluster pcsd-status %(node_name)s' % module.params)
+
+ if state == 'present' and rc != 0:
+ # WARNING: this will also consider nodes to which we cannot connect as unauthorized
+ result['changed'] = True
+ if not module.check_mode:
+ if pcs_version == '0.9':
+ cmd_auth = 'pcs cluster auth %(node_name)s -u %(username)s -p %(password)s --local' % module.params
+ elif pcs_version == '0.10':
+ cmd_auth = 'pcs host auth %(node_name)s -u %(username)s -p %(password)s' % module.params
+ else:
+ module.fail_json(msg="unsupported version of pcs (" + pcs_version + "). Only versions 0.9 and 0.10 are supported.")
+ rc, out, err = module.run_command(cmd_auth)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to authenticate node using command '" + cmd_auth + "'", output=out, error=err)
+
+ elif (state == 'absent' and tokens_data and (
+ (pcs_version == '0.9' and node_name in tokens_data['tokens']) or
+ (pcs_version == '0.10' and node_name in tokens_data['known_hosts'])
+ )):
+ result['changed'] = True
+ if not module.check_mode:
+ if pcs_version == '0.9':
+ del tokens_data['tokens'][node_name]
+ del tokens_data['ports'][node_name]
+ tokens_data['data_version'] += 1
+ # write the change into token file
+ tokens_file.seek(0)
+ json.dump(tokens_data, tokens_file, indent=4)
+ tokens_file.truncate()
+ elif pcs_version == '0.10':
+ cmd_deauth = 'pcs host deauth %(node_name)s' % module.params
+ rc, out, err = module.run_command(cmd_deauth)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to de-authenticate node using command '" + cmd_deauth + "'", output=out, error=err)
+ else:
+ module.fail_json(msg="unsupported version of pcs (" + pcs_version + "). Only versions 0.9 and 0.10 are supported.")
+
+ else:
+ result['changed'] = False
+ module.exit_json(**result)
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_cluster.py b/library/pcs_cluster.py
new file mode 100644
index 0000000..65037f5
--- /dev/null
+++ b/library/pcs_cluster.py
@@ -0,0 +1,325 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_cluster
+short_description: "wrapper module for 'pcs cluster setup/destroy/node add/node remove'"
+description:
+ - "module for creating/destroying/extending/shrinking clusters using 'pcs' utility"
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that cluster exists"
+ - "'absent' - ensure cluster doesn't exist"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ node_list:
+ description:
+ - space separated list of nodes in cluster
+ required: false
+ type: str
+ cluster_name:
+ description:
+ - pacemaker cluster name
+ required: false
+ type: str
+ token:
+ description:
+ - sets time in milliseconds until a token loss is declared after not receiving a token
+ required: false
+ type: int
+ transport:
+ description:
+ - "'default' - use default transport protocol ('udp' in CentOS/RHEL 6, 'udpu' in CentOS/RHEL 7), 'knet' in Fedora 29"
+ - "'udp' - use UDP multicast protocol"
+ - "'udpu' - use UDP unicast protocol"
+ - "'knet' - use KNET protocol"
+ required: false
+ default: default
+ choices: ['default', 'udp', 'udpu', 'knet']
+ type: str
+ transport_options:
+ description:
+ - "additional options for transports (available only with pcs-0.10), this option can be used only when `transport` option is specified (non-default)"
+ required: false
+ type: str
+ allowed_node_changes:
+ description:
+ - "'none' - node list must match existing cluster if cluster should be present"
+ - "'add' - allow adding new nodes to cluster"
+ - "'remove' - allow removing nodes from cluster"
+ default: none
+ required: false
+ choices: ['none', 'add', 'remove']
+ type: str
+notes:
+ - Tested on CentOS 6.8, 6.9, 7.3, 7.4, 7.5
+ - Tested on Red Hat Enterprise Linux 7.3, 7.4, 7.6
+ - "When adding/removing nodes, make sure to use 'run_once=True' and 'delegate_to' that points to
+ node that will stay in cluster, nodes cannot add themselves to cluster and node that removes
+ themselves may not remove all needed cluster information
+ - https://bugzilla.redhat.com/show_bug.cgi?id=1360882"
+ - redundant link support tested on CentOS 7.8 with 2 links and on CentOS 8.2 with 3 links and knet
+'''
+
+EXAMPLES = '''
+- name: Setup cluster
+ pcs_cluster:
+ node_list: "{% for item in play_hosts %}{{ hostvars[item]['ansible_hostname'] }} {% endfor %}"
+ cluster_name: 'test-cluster'
+ run_once: True
+
+- name: Create cluster with totem token timeout of 5000 ms and UDP unicast transport protocol
+ pcs_cluster:
+ node_list: "{% for item in play_hosts %}{{ hostvars[item]['ansible_hostname'] }} {% endfor %}"
+ cluster_name: 'test-cluster'
+ token: 5000
+ transport: 'udpu'
+ run_once: True
+
+- name: Create cluster with redundant corosync links
+ pcs_cluster:
+ cluster_name: 'test-cluster'
+ node_list: >
+ node1.example.com,192.168.1.11
+ node2.example.com,192.168.1.12
+ state: 'present'
+ run_once: True
+
+- name: Create cluster with two redundant corosync links and transport and link options
+ pcs_cluster:
+ cluster_name: 'test-cluster'
+ node_list: >
+ node1.example.com,192.168.1.11,192.168.2.11
+ node2.example.com,192.168.1.12,192.168.2.12
+ transport: 'knet'
+ transport_options: link_mode=passive link linknumber=0 transport=udp link_priority=1 link linknumber=1 transport=udp link_priority=2'
+ run_once: True
+
+- name: Add new nodes to existing cluster
+ pcs_cluster:
+ node_list: 'existing-node-1 existing-node-2 new-node-3 new-node-4'
+ cluster_name: 'test-cluster'
+ allowed_node_changes: 'add'
+ run_once: True
+ delegate_to: existing-node-1
+
+- name: Remove nodes from existing cluster cluster (test-cluster= exiting-node-1, exiting-node-2, exiting-node-3, exiting-node-4)
+ pcs_cluster:
+ node_list: 'existing-node-1 existing-node-2'
+ cluster_name: 'test-cluster'
+ allowed_node_changes: 'remove'
+ run_once: True
+ delegate_to: existing-node-1
+
+- name: Destroy cluster on each node
+ pcs_cluster:
+ state: 'absent'
+'''
+
+import os.path
+import re
+from distutils.spawn import find_executable
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ node_list=dict(required=False),
+ cluster_name=dict(required=False),
+ token=dict(required=False, type='int'),
+ transport=dict(required=False, default="default", choices=['default', 'udp', 'udpu', 'knet']),
+ transport_options=dict(required=False, default="", type='str'),
+ allowed_node_changes=dict(required=False, default="none", choices=['none', 'add', 'remove']),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ allowed_node_changes = module.params['allowed_node_changes']
+ node_list = module.params['node_list']
+ if state == 'present' and (not module.params['node_list'] or not module.params['cluster_name']):
+ module.fail_json(msg='When creating/expanding/shrinking cluster you must specify both node_list and cluster_name')
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ # get the pcs major.minor version
+ rc, out, err = module.run_command('pcs --version')
+ if rc == 0:
+ pcs_version = out.split('.')[0] + '.' + out.split('.')[1]
+ else:
+ module.fail_json(msg="pcs --version exited with non-zero exit code (" + rc + "): " + out + err)
+
+ # /var/lib/pacemaker/cib/cib.xml exists on cluster that were at least once started
+ cib_xml_exists = os.path.isfile('/var/lib/pacemaker/cib/cib.xml')
+ # EL 6 configuration file
+ cluster_conf_exists = os.path.isfile('/etc/cluster/cluster.conf')
+ # EL 7 configuration file
+ corosync_conf_exists = os.path.isfile('/etc/corosync/corosync.conf')
+
+ node_list_set = set()
+ node_list_set_detailed = {}
+ if node_list is not None:
+ # process node list (use only first node name (ring0)
+ for item in node_list.split():
+ node_list_set.add(item.split(',')[0])
+ node_list_set_detailed[item.split(',')[0]] = {'ring0': item.split(',')[0]}
+ if len(item.split(',')) > 1:
+ for ring_num in range(len(item.split(',')) - 1):
+ node_list_set_detailed[item.split(',')[0]]['ring' + str(ring_num + 1)] = item.split(',')[ring_num + 1]
+
+ detected_node_list_set = set()
+ if corosync_conf_exists:
+ try:
+ corosync_conf = open('/etc/corosync/corosync.conf', 'r')
+ nodes = re.compile(r"node\s*\{([^}]+)\}", re.M + re.S)
+ # parse list of nodes with their parameters from corosync.conf
+ re_nodes_list = nodes.findall(corosync_conf.read())
+ except IOError as e:
+ detected_node_list_set = set()
+
+ re_node_list_set = {}
+ if len(re_nodes_list) == 0:
+ detected_node_list_set = set()
+ exit
+
+ # detect ring_0 address that will become node_name
+ node_name = re.compile(r"ring0_addr\s*:\s*([\w.-]+)\s*", re.M)
+ for node in re_nodes_list:
+ n_name = node_name.search(node)
+ if n_name is None:
+ # skip node if we cannot determine it's ring0 address
+ continue
+ re_node_list_set[n_name.group(1)] = {'ring0': n_name.group(1)}
+ detected_node_list_set.add(n_name.group(1))
+ # detect additional ring addresses
+ for ring_num in range(7):
+ node_rings = re.compile(r"ring" + str(ring_num + 1) + r"_addr\s*:\s*([\w.-]+)\s*", re.M)
+ n_rings = node_rings.search(node)
+ if n_rings:
+ re_node_list_set[n_name.group(1)]["ring" + str(ring_num + 1)] = n_rings.group(1)
+
+ # if there is no cluster configuration and cluster should be created do 'pcs cluster setup'
+ if state == 'present' and not (cluster_conf_exists or corosync_conf_exists or cib_xml_exists):
+ result['changed'] = True
+ # create cluster from node list that was provided to module
+ if pcs_version == '0.9':
+ # if no transport_options are specified used empty string
+ if (module.params['transport_options']):
+ module.fail_json(msg="using transport_options is not supported with pcs 0.9")
+ module.params['token_param'] = '' if (not module.params['token']) else '--token %(token)s' % module.params
+ module.params['transport_param'] = '' if (module.params['transport'] == 'default') else '--transport %(transport)s' % module.params
+ cmd = 'pcs cluster setup --name %(cluster_name)s %(node_list)s %(token_param)s %(transport_param)s' % module.params
+ elif pcs_version == '0.10':
+ if ((module.params['transport_options'] != '') and (module.params['transport'] == 'default')):
+ module.fail_json(msg="using option transport_option must not be used without option transport")
+ module.params['token_param'] = '' if (not module.params['token']) else 'token %(token)s' % module.params
+ module.params['transport_param'] = '' if (module.params['transport'] == 'default') else 'transport %(transport)s' % module.params
+ if ',' in module.params['node_list']:
+ # rewrite node_list to conform to pcs-0.10 format with multiple links
+ module.params['node_list'] = ''
+ for node in node_list_set:
+ module.params['node_list'] += node + ' '
+ for link_number in range(len(node_list_set_detailed[node])):
+ module.params['node_list'] += 'addr=' + node_list_set_detailed[node]['ring' + str(link_number)] + ' '
+ cmd = 'pcs cluster setup %(cluster_name)s %(node_list)s %(token_param)s %(transport_param)s %(transport_options)s' % module.params
+ else:
+ module.fail_json(msg="unsupported version of pcs (" + pcs_version + "). Only versions 0.9 and 0.10 are supported.")
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ module.exit_json(changed=True)
+ else:
+ module.fail_json(msg="Failed to create cluster using command '" + cmd + "'", output=out, error=err)
+ # if cluster exists and we are allowed to add/remove nodes do 'pcs cluster node add/remove'
+ elif state == 'present' and corosync_conf_exists and allowed_node_changes != 'none' and node_list_set != detected_node_list_set:
+ result['changed'] = True
+ result['detected_nodes'] = detected_node_list_set
+ # adding new nodes to cluster
+ if allowed_node_changes == 'add':
+ result['nodes_to_add'] = node_list_set - detected_node_list_set
+ for node in (node_list_set - detected_node_list_set):
+ if 'ring1' in node_list_set_detailed[node] and pcs_version == '0.9':
+ cmd = 'pcs cluster node add ' + node + ',' + node_list_set_detailed[node]['ring1']
+ elif len(node_list_set_detailed[node]) > 1 and pcs_version == '0.10':
+ cmd = 'pcs cluster node add ' + node + ' '
+ for link_number in range(len(node_list_set_detailed[node])):
+ cmd += 'addr=' + node_list_set_detailed[node]['ring' + str(link_number)] + ' '
+ else:
+ cmd = 'pcs cluster node add ' + node
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ module.exit_json(changed=True)
+ else:
+ module.fail_json(msg="Failed to add node '" + node + "' to cluster using command '" + cmd + "'", output=out, error=err)
+ # removing nodes from cluster
+ if allowed_node_changes == 'remove':
+ result['nodes_to_remove'] = detected_node_list_set - node_list_set
+ for node in (detected_node_list_set - node_list_set):
+ cmd = 'pcs cluster node remove ' + node
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ module.exit_json(changed=True)
+ else:
+ module.fail_json(msg="Failed to remove node '" + node + "' from cluster using command '" + cmd + "'", output=out, error=err)
+ # if cluster should be removed and cluster configuration exists
+ elif state == 'absent' and (cluster_conf_exists or corosync_conf_exists or cib_xml_exists):
+ result['changed'] = True
+ # destroy cluster on node where this module is executed
+ cmd = 'pcs cluster destroy'
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ module.exit_json(changed=True)
+ else:
+ module.fail_json(msg="Failed to delete cluster using command '" + cmd + "'", output=out, error=err)
+ # if cluster doesn't exists and should be removed, just acknowledge that no chage is needed
+ elif state == 'absent' and (not cluster_conf_exists and not corosync_conf_exists and not cib_xml_exists):
+ module.exit_json(changed=False, msg="No change needed, cluster is not present.")
+ # if the cluster looks as it should
+ elif state == 'present' and corosync_conf_exists and node_list_set == detected_node_list_set:
+ module.exit_json(changed=False, msg="No change needed, cluster is present.")
+ # if requested node list and detected node list are different but we are not allowed to change, fail
+ elif state == 'present' and corosync_conf_exists and allowed_node_changes == 'none' and node_list_set != detected_node_list_set:
+ module.fail_json(
+ msg="'Detected node list' and 'Requested node list' are different, but changes are not allowed.",
+ node_list_set=node_list_set,
+ detected_node_list_set=detected_node_list_set
+ )
+ else:
+ # all other cases, possibly also unhadled ones
+ module.exit_json(changed=False)
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_constraint_colocation.py b/library/pcs_constraint_colocation.py
new file mode 100644
index 0000000..195a64c
--- /dev/null
+++ b/library/pcs_constraint_colocation.py
@@ -0,0 +1,248 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_constraint_colocation
+short_description: "wrapper module for 'pcs constraint colocation'"
+description:
+ - "module for creating and deleting clusters colocation constraints using 'pcs' utility"
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that cluster constraint exists"
+ - "'absent' - ensure cluster constraints doesn't exist"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ resource1:
+ description:
+ - first resource for constraint
+ required: true
+ type: str
+ resource2:
+ description:
+ - second resource for constraint
+ required: true
+ type: str
+ resource1_role:
+ description:
+ - Role of resource1
+ required: false
+ choices: ['Master', 'Slave', 'Started']
+ default: 'Started'
+ type: str
+ resource2_role:
+ description:
+ - Role of resource2
+ required: false
+ choices: ['Master', 'Slave', 'Started']
+ default: 'Started'
+ type: str
+ score:
+ description:
+ - constraint score in range -INFINITY..0..INFINITY
+ required: false
+ default: 'INFINITY'
+ type: str
+ cib_file:
+ description:
+ - "Apply changes to specified file containing cluster CIB instead of running cluster."
+ - "This module requires the file to already contain cluster configuration."
+ required: false
+ type: str
+notes:
+ - tested on CentOS 7.6, Fedora 29
+ - no extra options allowed for constraints
+ - "TODO: validation of resource names, score values"
+'''
+
+EXAMPLES = '''
+- name: prefer resA and resB to run on same node
+ pcs_constraint_colocation:
+ resource1: 'resA'
+ resource2: 'resB'
+
+- name: prefer resA to run on same node as Master resource of resB-master resource
+ pcs_constraint_colocation:
+ resource1: 'resA'
+ resource2: 'resB-master'
+ resource2_role: 'Master'
+
+- name: remove colocation constraint that prefer resA to run on same node as Master resource of resB-master resource
+ pcs_constraint_colocation:
+ resource1: 'resA'
+ resource2: 'resB-master'
+ resource2_role: 'Master'
+ state: 'absent'
+'''
+
+import os.path
+import xml.etree.ElementTree as ET
+from distutils.spawn import find_executable
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ resource1=dict(required=True),
+ resource2=dict(required=True),
+ resource1_role=dict(required=False, choices=['Master', 'Slave', 'Started'], default='Started'),
+ resource2_role=dict(required=False, choices=['Master', 'Slave', 'Started'], default='Started'),
+ score=dict(required=False, default="INFINITY"),
+ cib_file=dict(required=False),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ resource1 = module.params['resource1']
+ resource2 = module.params['resource2']
+ resource1_role = module.params['resource1_role']
+ resource2_role = module.params['resource2_role']
+ score = module.params['score']
+ cib_file = module.params['cib_file']
+
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ module.params['cib_file_param'] = ''
+ if cib_file is not None:
+ # use cib_file if specified
+ if os.path.isfile(cib_file):
+ try:
+ current_cib = ET.parse(cib_file)
+ except Exception as e:
+ module.fail_json(msg="Error encountered parsing the cib_file - %s" % (e))
+ current_cib_root = current_cib.getroot()
+ module.params['cib_file_param'] = '-f ' + cib_file
+ else:
+ module.fail_json(msg="%(cib_file)s is not a file or doesn't exists" % module.params)
+ else:
+ # get running cluster configuration
+ rc, out, err = module.run_command('pcs cluster cib')
+ if rc == 0:
+ current_cib_root = ET.fromstring(out)
+ else:
+ module.fail_json(msg='Failed to load cluster configuration', out=out, error=err)
+
+ # try to find the constraint we have defined
+ constraint = None
+ with_roles = False
+ detected_role1, detected_role2 = None, None
+ # check if we have requested a non-default roles
+ if resource1_role != 'Started' or resource2_role != 'Started':
+ with_roles = True
+ constraints = current_cib_root.findall("./configuration/constraints/rsc_colocation")
+ for constr in constraints:
+ # constraint is matched using following criteria:
+ # - resource order (resource1 with resource2)
+ # - resource roles (resource1_role with resource2_role)
+ if (constr.attrib.get('rsc') == resource1
+ and constr.attrib.get('with-rsc') == resource2
+ and constr.attrib.get('rsc-role', 'Started') == resource1_role
+ and constr.attrib.get('with-rsc-role', 'Started') == resource2_role):
+ constraint = constr
+ break
+
+ # additional variables for verbose output
+ if constraint is not None:
+ result.update({
+ 'constraint_was_matched': True,
+ 'score': constraint.attrib.get('score'),
+ 'resource1_role': constr.attrib.get('rsc-role'),
+ 'resource2_role': constr.attrib.get('with-rsc-role'),
+ })
+ else:
+ result.update({'constraint_was_matched': False})
+
+ # colocation constraint creation command
+ # TODO: check which old versions requires this, the 0.9.162 seems to handle 'Started' role correctly
+ if with_roles is True:
+ if resource1_role != 'Started' and resource2_role != 'Started':
+ cmd_create = """ pcs %(cib_file_param)s constraint colocation
+ add %(resource1_role)s %(resource1)s
+ with %(resource2_role)s %(resource2)s %(score)s """ % module.params
+ elif resource1_role != 'Started' and resource2_role == 'Started':
+ cmd_create = """ pcs %(cib_file_param)s constraint colocation
+ add %(resource1_role)s %(resource1)s
+ with %(resource2)s %(score)s """ % module.params
+ elif resource1_role == 'Started' and resource2_role != 'Started':
+ cmd_create = """ pcs %(cib_file_param)s constraint colocation
+ add %(resource1)s
+ with %(resource2_role)s %(resource2)s %(score)s """ % module.params
+ else:
+ cmd_create = """ pcs %(cib_file_param)s constraint colocation
+ add %(resource1)s with %(resource2)s %(score)s """ % module.params
+
+ # colocation constraint deletion command
+ if constraint is not None:
+ cmd_delete = 'pcs %(cib_file_param)s constraint delete ' % module.params + constraint.attrib.get('id')
+
+ if state == 'present' and constraint is None:
+ # constraint should be present, but we don't see it in configuration - lets create it
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_create)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to create constraint with cmd: '" + cmd_create + "'", output=out, error=err)
+
+ elif state == 'present' and constraint is not None:
+ # constraint should be present, lets see if it has different score from requested, if yes, then we do update
+ if constraint.attrib.get('score', 'INFINITY') != score:
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_delete)
+ if rc != 0:
+ module.fail_json(msg="Failed to delete constraint for replacement with cmd: '" + cmd_delete + "'", output=out, error=err)
+ else:
+ rc, out, err = module.run_command(cmd_create)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to create constraint replacement with cmd: '" + cmd_create + "'", output=out, error=err)
+
+ elif state == 'absent' and constraint is not None:
+ # constraint should not be present but we have found something - lets remove that
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_delete)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to delete constraint with cmd: '" + cmd_delete + "'", output=out, error=err)
+ else:
+ # constraint should not be present and is not there, nothing to do
+ result['changed'] = False
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_constraint_location.py b/library/pcs_constraint_location.py
new file mode 100644
index 0000000..2f30661
--- /dev/null
+++ b/library/pcs_constraint_location.py
@@ -0,0 +1,199 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_constraint_location
+short_description: "wrapper module for 'pcs constraint location'"
+description:
+ - "module for creating and deleting clusters location constraints using 'pcs' utility"
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that cluster constraint exists"
+ - "'absent' - ensure cluster constraints doesn't exist"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ resource:
+ description:
+ - resource for constraint
+ required: true
+ type: str
+ node_name:
+ description:
+ - node name for constraints
+ required: true
+ type: str
+ score:
+ description:
+ - constraint score in range -INFINITY..0..INFINITY
+ required: false
+ default: 'INFINITY'
+ type: str
+ cib_file:
+ description:
+ - "Apply changes to specified file containing cluster CIB instead of running cluster."
+ - "This module requires the file to already contain cluster configuration."
+ required: false
+ type: str
+notes:
+ - tested on CentOS 7.6, Fedora 29
+ - specifying non-existing node_name for Fedora 29 produces error. Use only existing node names.
+'''
+
+EXAMPLES = '''
+- name: resource resA prefers to run on node1
+ pcs_constraint_location:
+ resource: 'resA'
+ node_name: 'node1'
+
+- name: remove constraint where resource resA prefers to run on node1
+ pcs_constraint_location:
+ resource: 'resA'
+ node_name: 'node1'
+ state: 'absent'
+
+- name: resource resB avoids running on node2
+ pcs_constraint_location:
+ resource: 'resB'
+ node_name: 'node2'
+ score: '-INFINITY'
+
+- name: remove constraint where resource resB avoids running on node2
+ pcs_constraint_location:
+ resource: 'resB'
+ node_name: 'node2'
+ score: '-INFINITY'
+ state: 'absent'
+'''
+
+import os.path
+import xml.etree.ElementTree as ET
+from distutils.spawn import find_executable
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ resource=dict(required=True),
+ node_name=dict(required=True),
+ score=dict(required=False, default="INFINITY"),
+ cib_file=dict(required=False),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ resource = module.params['resource']
+ node_name = module.params['node_name']
+ score = module.params['score']
+ cib_file = module.params['cib_file']
+
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ module.params['cib_file_param'] = ''
+ if cib_file is not None:
+ # use cib_file if specified
+ if os.path.isfile(cib_file):
+ try:
+ current_cib = ET.parse(cib_file)
+ except Exception as e:
+ module.fail_json(msg="Error encountered parsing the cib_file - %s" % (e))
+ current_cib_root = current_cib.getroot()
+ module.params['cib_file_param'] = '-f ' + cib_file
+ else:
+ module.fail_json(msg="%(cib_file)s is not a file or doesn't exists" % module.params)
+ else:
+ # get running cluster configuration
+ rc, out, err = module.run_command('pcs cluster cib')
+ if rc == 0:
+ current_cib_root = ET.fromstring(out)
+ else:
+ module.fail_json(msg='Failed to load cluster configuration', out=out, error=err)
+
+ # try to find the constraint we have defined
+ constraint = None
+ constraints = current_cib_root.findall("./configuration/constraints/rsc_location")
+ for constr in constraints:
+ # constraint is considered found if we see resource and node as got through attributes
+ if constr.attrib.get('rsc') == resource and constr.attrib.get('node') == node_name:
+ constraint = constr
+ break
+
+ # location constraint creation command
+ cmd_create = 'pcs %(cib_file_param)s constraint location %(resource)s prefers %(node_name)s=%(score)s' % module.params
+
+ # location constriaint deleter command
+ if constraint is not None:
+ cmd_delete = 'pcs %(cib_file_param)s constraint delete ' % module.params + constraint.attrib.get('id')
+
+ if state == 'present' and constraint is None:
+ # constraint should be present, but we don't see it in configuration - lets create it
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_create)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to create constraint with cmd: '" + cmd_create + "'", output=out, error=err)
+
+ elif state == 'present' and constraint is not None:
+ # constraint should be present and we see similar constraint so lets check if it is same
+ if score != constraint.attrib.get('score'):
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_delete)
+ if rc != 0:
+ module.fail_json(msg="Failed to delete constraint for replacement with cmd: '" + cmd_delete + "'", output=out, error=err)
+ else:
+ rc, out, err = module.run_command(cmd_create)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to create constraint replacement with cmd: '" + cmd_create + "'", output=out, error=err)
+
+ elif state == 'absent' and constraint is not None:
+ # constraint should not be present but we have found something - lets remove that
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_delete)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to delete constraint with cmd: '" + cmd_delete + "'", output=out, error=err)
+ else:
+ # constraint should not be present and is not there, nothing to do
+ result['changed'] = False
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_constraint_order.py b/library/pcs_constraint_order.py
new file mode 100644
index 0000000..41b9f26
--- /dev/null
+++ b/library/pcs_constraint_order.py
@@ -0,0 +1,256 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_constraint_order
+short_description: "wrapper module for 'pcs constraint order'"
+description:
+ - "module for creating and deleting clusters order constraints using 'pcs' utility"
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that cluster constraint exists"
+ - "'absent' - ensure cluster constraints doesn't exist"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ resource1:
+ description:
+ - first resource for constraint
+ required: true
+ type: str
+ resource2:
+ description:
+ - second resource for constraint
+ required: true
+ type: str
+ resource1_action:
+ description:
+ - action to which constraint applies for resource1
+ required: false
+ choices: ['start','promote','demote','stop']
+ default: 'start'
+ type: str
+ resource2_action:
+ description:
+ - action to which constraint applies for resource2
+ required: false
+ choices: ['start','promote','demote','stop']
+ default: 'start'
+ type: str
+ kind:
+ description:
+ - Kind of the order constraint
+ required: false
+ choices: ['Optional','Mandatory','Serialize']
+ default: 'Mandatory'
+ type: str
+ symmetrical:
+ description:
+ - Is the constraint symmetrical?
+ required: false
+ choices: ['true','false']
+ default: 'true'
+ type: str
+ cib_file:
+ description:
+ - "Apply changes to specified file containing cluster CIB instead of running cluster."
+ - "This module requires the file to already contain cluster configuration."
+ required: false
+ type: str
+notes:
+ - tested on CentOS 7.6, Fedora 29
+'''
+
+EXAMPLES = '''
+- name: start resA before starting resB
+ pcs_constraint_order:
+ resource1: 'resA'
+ resource2: 'resB'
+
+- name: make Optional order constraint where resA should start before resB
+ pcs_constraint_order:
+ resource1: 'resA'
+ resource2: 'resB'
+ kind: 'Optional'
+
+- name: start resB after resA was promoted
+ pcs_constraint_order:
+ resource1: 'resA'
+ resource1_action: 'promote'
+ resource2: 'resB'
+
+- name: start resA before starting resB but don't require that resB stope before resA
+ pcs_constraint_order:
+ resource1: 'resA'
+ resource2: 'resB'
+ symmetrical: 'false'
+
+- name: remove order constraint between resA and resB
+ pcs_constraint_order:
+ resource1: 'resA'
+ resource2: 'resB'
+ state: 'absent'
+'''
+
+import os.path
+import xml.etree.ElementTree as ET
+from distutils.spawn import find_executable
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ resource1=dict(required=True),
+ resource2=dict(required=True),
+ resource1_action=dict(required=False, choices=['start', 'promote', 'demote', 'stop'], default='start'),
+ resource2_action=dict(required=False, choices=['start', 'promote', 'demote', 'stop'], default='start'),
+ kind=dict(required=False, choices=['Optional', 'Mandatory', 'Serialize'], default='Mandatory'),
+ symmetrical=dict(required=False, choices=['true', 'false'], default='true'),
+ cib_file=dict(required=False),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ resource1 = module.params['resource1']
+ resource2 = module.params['resource2']
+ resource1_action = module.params['resource1_action']
+ resource2_action = module.params['resource2_action']
+ kind = module.params['kind']
+ symmetrical = module.params['symmetrical']
+ cib_file = module.params['cib_file']
+
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ module.params['cib_file_param'] = ''
+ if cib_file is not None:
+ # use cib_file if specified
+ if os.path.isfile(cib_file):
+ try:
+ current_cib = ET.parse(cib_file)
+ except Exception as e:
+ module.fail_json(msg="Error encountered parsing the cib_file - %s" % (e))
+ current_cib_root = current_cib.getroot()
+ module.params['cib_file_param'] = '-f ' + cib_file
+ else:
+ module.fail_json(msg="%(cib_file)s is not a file or doesn't exists" % module.params)
+ else:
+ # get running cluster configuration
+ rc, out, err = module.run_command('pcs cluster cib')
+ if rc == 0:
+ current_cib_root = ET.fromstring(out)
+ else:
+ module.fail_json(msg='Failed to load cluster configuration', out=out, error=err)
+
+ # try to find the constraint we have defined
+ constraint = None
+ constraints = current_cib_root.findall("./configuration/constraints/rsc_order")
+ for constr in constraints:
+ # constraint is matched using following criteria:
+ # - resource order (resource1 then resource2)
+ # - resource actions (resource1_action then resource2_action)
+ # only if above is matched, the constraint is considered to match
+ if (constr.attrib.get('first') == resource1
+ and constr.attrib.get('then') == resource2
+ and constr.attrib.get('first-action', 'start') == resource1_action
+ and constr.attrib.get('then-action', 'start') == resource2_action):
+ constraint = constr
+ break
+
+ # additional variables for verbose output on matching the constraint
+ if constraint is not None:
+ result.update({
+ 'constraint_was_matched': True,
+ 'resource1_action': None if constraint is None else constraint.attrib.get('first-action'),
+ 'resource2_action': None if constraint is None else constraint.attrib.get('then-action'),
+ 'kind': None if constraint is None else constraint.attrib.get('kind'),
+ 'symmetrical': None if constraint is None else constraint.attrib.get('symmetrical'),
+ })
+ else:
+ result.update({'constraint_was_matched': False})
+
+ # order constraint creation command
+ cmd_create = """ pcs %(cib_file_param)s constraint
+ order %(resource1_action)s %(resource1)s
+ then %(resource2_action)s %(resource2)s
+ kind=%(kind)s symmetrical=%(symmetrical)s """ % module.params
+
+ # order constraint deletion command
+ if constraint is not None:
+ cmd_delete = 'pcs %(cib_file_param)s constraint delete ' % module.params + constraint.attrib.get('id')
+
+ if state == 'present' and constraint is None:
+ # constraint should be present, but we don't see it in configuration - lets create it
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_create)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to create constraint with cmd: '" + cmd_create + "'", output=out, error=err)
+
+ elif state == 'present' and constraint is not None:
+ # constraint should be present, let see if the relevant attributes are different (if yes, then we need an update)
+ # constraint is considered different if following attributes are different:
+ # - symmetrical (true, false)
+ # - kind (Mandatory, Optional, Serialize)
+ if constraint.attrib.get('kind', 'Mandatory') != kind or constraint.attrib.get('symmetrical', 'true') != symmetrical:
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_delete)
+ if rc != 0:
+ module.fail_json(msg="Failed to delete constraint for replacement with cmd: '" + cmd_delete + "'",
+ output=out, error=err)
+ else:
+ rc, out, err = module.run_command(cmd_create)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to create constraint replacement with cmd: '" + cmd_create + "'",
+ output=out, error=err, cmd_del=cmd_delete)
+
+ elif state == 'absent' and constraint is not None:
+ # constraint should not be present but we have found something - lets remove that
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_delete)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to delete constraint with cmd: '" + cmd_delete + "'", output=out, error=err)
+ else:
+ # constraint should not be present and is not there, nothing to do
+ result['changed'] = False
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_property b/library/pcs_property
deleted file mode 100644
index a36d857..0000000
--- a/library/pcs_property
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-
-DOCUMENTATION = '''
----
-module: pcs_property
-short_description: Manages I(pacemaker) cluster properties with pcs tool.
-options:
- state:
- required: false
- default: present
- choices: [ "absent", "present" ]
- name:
- required: true
- description: name of the property.
- value:
- required: true
- description: value of the property.
-'''
-
-def main():
- module = AnsibleModule(
- argument_spec = dict(
- state = dict(default='present', choices=['present', 'absent']),
- name = dict(required=True),
- value = dict(required=True),
- ),
- supports_check_mode=True,
- )
-
- # TODO check pcs command is available.
- # TODO check pacemaker/corosync is running.
-
- # Get current property value.
- cmd = "pcs property list %(name)s | awk '/^ / { print $2}'" % module.params
- rc, out, err = module.run_command(cmd, use_unsafe_shell=True)
- value = out.strip()
-
- if module.params['state'] == 'absent':
- print "absent?=?"
- if value != '':
- changed = True
- if not module.check_mode:
- cmd = 'pcs property unset %(name)s' % module.params
- module.run_command(cmd)
- else:
- changed = False
- module.exit_json(changed=changed)
- else:
- print "VALUES: %s - %s" % (value, module.params['value'])
- if value != module.params['value']:
- changed = True
- if not module.check_mode:
- cmd = 'pcs property set %(name)s=%(value)s' % module.params
- module.run_command(cmd)
- else:
- changed = False
- module.exit_json(changed=changed, prev="|%s|" % value, msg="%(name)s=%(value)s" % module.params)
-
-# import module snippets
-from ansible.module_utils.basic import *
-main()
-
diff --git a/library/pcs_property.py b/library/pcs_property.py
new file mode 100644
index 0000000..a338d82
--- /dev/null
+++ b/library/pcs_property.py
@@ -0,0 +1,197 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_property
+short_description: "wrapper module for 'pcs property'"
+description:
+ - "module for setting and unsetting cluster and node properties using 'pcs' utility"
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that cluster property exists with given value"
+ - "'absent' - ensure cluster property doesn't exist (is unset)"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ name:
+ description:
+ - name of cluster property
+ required: true
+ type: str
+ node:
+ description:
+ - node name for node-specific property
+ required: false
+ type: str
+ value:
+ description:
+ - value of cluster property
+ required: false
+ type: str
+ cib_file:
+ description:
+ - "Apply changes to specified file containing cluster CIB instead of running cluster."
+ required: false
+ type: str
+notes:
+ - Tested on CentOS 7.6, Fedora 28, 29
+ - Tested on Red Hat Enterprise Linux 7.6
+ - node property values with spaces are not idempotent
+'''
+
+EXAMPLES = '''
+- name: set maintenance mode cluster property (enable maintenance mode)
+ pcs_property:
+ name: 'maintenance-mode'
+ value: 'true'
+
+- name: unset maintenance mode cluster property (disable maintenance mode)
+ pcs_property:
+ name: 'maintenance-mode'
+ state: 'absent'
+
+- name: set property 'standby' to 'on' for node 'node-1' (standby node-1)
+ pcs_property:
+ name: 'standby'
+ node: 'node-1'
+ value: 'on'
+
+- name: remove 'standby' node attribute from 'node-1' (unstandby node-1)
+ pcs_property:
+ name: 'standby'
+ node: 'node-1'
+ state: 'absent'
+'''
+
+import os.path
+import re
+from distutils.spawn import find_executable
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ name=dict(required=True),
+ node=dict(required=False),
+ value=dict(required=False),
+ cib_file=dict(required=False),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ name = module.params['name']
+ value = module.params['value']
+ node = module.params['node']
+ cib_file = module.params['cib_file']
+
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ if state == 'present' and value is None:
+ module.fail_json(msg="To set property 'value' must be specified.")
+
+ module.params['cib_file_param'] = ''
+ if cib_file is not None and os.path.isfile(cib_file):
+ module.params['cib_file_param'] = '-f ' + cib_file
+
+ # get property list from running cluster
+ if node is not None:
+ rc, out, err = module.run_command('pcs %(cib_file_param)s node attribute' % module.params)
+ else:
+ rc, out, err = module.run_command('pcs %(cib_file_param)s property show' % module.params)
+ properties = {}
+ if rc == 0:
+ # indicator in which part of parsing we are
+ property_type = None
+ properties['cluster'] = {}
+ properties['node'] = {}
+ # we are stripping last line as they doesn't contain properties
+ for row in out.split('\n')[0:-1]:
+ # based on row we see the section to either cluster or node properties
+ if row == 'Cluster Properties:':
+ property_type = 'cluster'
+ elif row == 'Node Attributes:':
+ property_type = 'node'
+ else:
+ # when identifier of section is not preset we are at the property
+ tmp = row.lstrip().split(':')
+ if property_type == 'cluster':
+ properties['cluster'][tmp[0]] = tmp[1].lstrip()
+ elif property_type == 'node':
+ properties['node'][tmp[0]] = {}
+ # FIXME: this matches only properties which values doesn't contain spaces
+ match_node_properties = re.compile(r"(\w+=\w+)\s*")
+ matched_properties = match_node_properties.findall(':'.join(tmp[1:]))
+ for prop in matched_properties:
+ properties['node'][tmp[0]][prop.split('=')[0]] = prop.split('=')[1]
+ else:
+ module.fail_json(msg='Failed to load properties from cluster. Is cluster running?')
+
+ result['detected_properties'] = properties
+
+ if state == 'present':
+ cmd_set = ''
+ result['changed'] = True
+ # property not found or having a different value
+ if node is None and (name not in properties['cluster'] or properties['cluster'][name] != value):
+ cmd_set = 'pcs %(cib_file_param)s property set %(name)s=%(value)s' % module.params
+ elif node is not None and (node not in properties['node'] or name not in properties['node'][node] or properties['node'][node][name] != value):
+ cmd_set = 'pcs %(cib_file_param)s node attribute %(node)s %(name)s=%(value)s' % module.params
+ else:
+ result['changed'] = False
+ if not module.check_mode and result['changed']:
+ rc, out, err = module.run_command(cmd_set)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to set property with cmd : '" + cmd_set + "'", output=out, error=err)
+
+ elif state == 'absent':
+ result['changed'] = True
+ cmd_unset = ''
+ # property found but it should not be set
+ if node is None and name in properties['cluster']:
+ cmd_unset = 'pcs %(cib_file_param)s property unset %(name)s' % module.params
+ elif node is not None and node in properties['node'] and name in properties['node'][node]:
+ cmd_unset = 'pcs %(cib_file_param)s node attribute %(node)s %(name)s=' % module.params
+ else:
+ result['changed'] = False
+ if not module.check_mode and result['changed']:
+ rc, out, err = module.run_command(cmd_unset)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to unset property with cmd: '" + cmd_unset + "'", output=out, error=err)
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_quorum_qdevice.py b/library/pcs_quorum_qdevice.py
new file mode 100644
index 0000000..ca89224
--- /dev/null
+++ b/library/pcs_quorum_qdevice.py
@@ -0,0 +1,212 @@
+#!/usr/bin/python
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Olivier Pouilly (@OliPou)"
+module: pcs_quorum_qdevice
+short_description: "wrapper module for 'pcs quorum setup/destroy/change qdevice setting'"
+description:
+ - "module for setup/destroy/change qdevice setting 'pcs' utility"
+version_added: "2.10"
+options:
+ state:
+ description:
+ - "'present' - ensure that the qdevice exists"
+ - "'absent' - ensure qdevice doesn't exist"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ qdevice:
+ description:
+ - qdevice name (hostname or IP address)
+ required: false
+ type: str
+ algorithm:
+ description:
+ - algorithm use by the cluster
+ required: false
+ choices: ['ffsplit', 'lms']
+ default: ffsplit
+ type: str
+ allowed_qdevice_changes:
+ description:
+ - "'none' - existing qdevice and algorithm must match"
+ - "'update' - allow qdevice and/or algorithm update"
+ default: none
+ required: false
+ choices: ['none', 'update']
+ type: str
+notes:
+ - Tested on Debian 10
+ - "When adding/removing qdevice, make sure to use 'run_once=True' on a cluster node"
+'''
+
+EXAMPLES = '''
+- name: Setup qdevice with default algorithm (ffsplit)
+ pcs_quorum_qdevice:
+ qdevice: qdevice-name
+ run_once: True
+
+- name: Setup qdevice with lms algorithm
+ pcs_quorum_qdevice:
+ qdevice: qdevice-name
+ algorithm: lms
+ run_once: True
+
+- name: Delete qdevice
+ pcs_quorum_qdevice:
+ state: absent
+ run_once: True
+
+- name: Setup or modify qdevice to use lms algorith
+ pcs_quorum_qdevice:
+ qdevice: qdevice-name
+ algorithm: lms
+ allowed_qdevice_changes: update
+ run_once: True
+'''
+
+import os.path
+import re
+from distutils.spawn import find_executable
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(required=False, default="present", choices=['present', 'absent']),
+ qdevice=dict(required=False, type='str'),
+ algorithm=dict(required=False, default="ffsplit", choices=['ffsplit', 'lms']),
+ allowed_qdevice_changes=dict(required=False, default="none", choices=['none', 'update']),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ allowed_qdevice_changes = module.params['allowed_qdevice_changes']
+ qdevice = module.params['qdevice']
+ algorithm = module.params['algorithm']
+ if state == 'present' and (not module.params['qdevice']):
+ module.fail_json(msg='When creating/updating qdevice you must specify qdevice name')
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ # get the pcs major.minor version
+ rc, out, err = module.run_command('pcs --version')
+ if rc == 0:
+ pcs_version = out.split('.')[0] + '.' + out.split('.')[1]
+ else:
+ module.fail_json(msg="pcs --version exited with non-zero exit code (" + rc + "): " + out + err)
+
+ if pcs_version != '0.10':
+ module.fail_json(msg="unsupported version of pcs (" + pcs_version + "). Only version 0.10 is supported.")
+
+ # EL 7 configuration file
+ corosync_conf_exists = os.path.isfile('/etc/corosync/corosync.conf')
+
+ if state == 'present' and not corosync_conf_exists:
+ module.fail_json(msg='When creating/updating qdevice you must have a cluster set')
+
+ try:
+ corosync_conf = open('/etc/corosync/corosync.conf', 'r')
+ qdevice_defined = re.compile(r"device\s*\{([^}]+)\}", re.M + re.S)
+ re_qdevice_defined = qdevice_defined.findall(corosync_conf.read())
+ except IOError as e:
+ module.fail_json(msg='Could not open corosync.conf')
+
+ if len(re_qdevice_defined) == 0:
+ no_conf, config_qdevice_name_diff, config_qdevice_algo_diff = True, False, False
+ else:
+ no_conf = False
+
+ qdevice_name = re.compile(r"host\s*:\s*([\w.-]+)\s*", re.M)
+ qd_name = qdevice_name.findall(re_qdevice_defined[0])
+
+ if len(qd_name) == 0 or qd_name[0] != qdevice:
+ config_qdevice_name_diff = True
+ else:
+ config_qdevice_name_diff = False
+
+ algorithm_name = re.compile(r"algorithm\s*:\s*([\w.-]+)\s*", re.M)
+ algo_name = algorithm_name.findall(re_qdevice_defined[0])
+ if len(algo_name) == 0 or algo_name[0] != algorithm:
+ config_qdevice_algo_diff = True
+ else:
+ config_qdevice_algo_diff = False
+
+ update, mismatch_options = False, False
+ msg = ''
+
+ if no_conf and state == 'present':
+ result['changed'] = True
+ result['new_qdevice'] = qdevice
+ result['new_algorithm'] = algorithm
+ cmd = 'pcs quorum device add model net host=%(qdevice)s algorithm=%(algorithm)s' % module.params
+ update = True
+
+ elif (config_qdevice_name_diff or config_qdevice_algo_diff) and allowed_qdevice_changes != 'none' and state == 'present':
+ result['changed'] = True
+ result['old_qdevice'] = qd_name
+ result['new_qdevice'] = qdevice
+ result['old_algorithm'] = algo_name
+ result['new_algorithm'] = algorithm
+ cmd = 'pcs quorum device update model host=%(qdevice)s algorithm=%(algorithm)s' % module.params
+ update = True
+
+ elif state == 'absent' and not no_conf:
+ result['changed'] = True
+ result['delete_qdevice'] = qd_name[0]
+ cmd = 'pcs quorum device remove'
+ update = True
+
+ if config_qdevice_name_diff and allowed_qdevice_changes == 'none' and state == 'present':
+ mismatch_options = True
+ result['qdevice'] = qdevice
+ result['qdevice_detected'] = qd_name
+
+ if config_qdevice_algo_diff and allowed_qdevice_changes == 'none' and state == 'present':
+ mismatch_options = True
+ result['algorithm'] = algorithm
+ result['algorithm_detected'] = algo_name
+
+ if mismatch_options:
+ if 'qdevice' in result:
+ msg += "'Detected qdevice' and 'Requested qdevice' are different, but changes are not allowed."
+ if 'algorithm' in result:
+ msg += "'Detected algorithm' and 'Requested algorithm' are different, but changes are not allowed."
+ result['msg'] = msg
+ module.fail_json(**result)
+
+ if not module.check_mode and update:
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to setup qdevice using command '" + cmd + "'", output=out, error=err)
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_resource b/library/pcs_resource
deleted file mode 100644
index 3bcf90a..0000000
--- a/library/pcs_resource
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-
-DOCUMENTATION = '''
----
-module: pcs_resource
-short_description: Manages I(pacemaker) cluster resources with pcs tool.
-options:
- command:
- required: true
- description: Supported commands.
- choices: [ "create", "master"]
- resource_id:
- required: true
- description: Id of the resource.
- type:
- required: true
- description: type of resource. Used in «create» command.
- ms_name:
- required: true
- description: name of the resource. Used in «master» command.
- group:
- required: false
- description: add the resource to specified group.
- options:
- required: false
- description: hash of resource options.
- operations:
- required: false
- description: list of hashes of operations. Used in «create» command.
- disabled:
- required: false
- type: bool
- description: don't start resource after creation.
-'''
-
-def main():
- module = AnsibleModule(
- argument_spec = dict(
- command = dict(choices=['create', 'master']),
- name = dict(required=True, aliases=['resource_id']),
- ms_name = dict(required=False, type='str'),
- type = dict(required=False),
- group = dict(required=False, type='str'),
- options = dict(required=False, type='dict'),
- operations = dict(required=False, type='raw'),
- disabled = dict(required=False, type='bool'),
- ),
- supports_check_mode=True,
- )
-
- # TODO check pcs command is available.
- # TODO check pacemaker/corosync is running.
-
- # Check if resource already exists.
- cmd = "pcs resource show %(name)s" % module.params
- rc, out, err = module.run_command(cmd)
- exists = (rc is 0)
-
- if exists:
- module.exit_json(changed=False, msg="Resource already exists.")
- elif module.check_mode:
- module.exit_json(changed=True)
-
- # Validate and process command specific params.
- if module.params['command'] == 'create':
- if not module.params.has_key('type'):
- module.fail_json(msg="missing required arguments: type.")
- if not module.params.has_key('options'):
- module.fail_json(msg="missing required arguments: options.")
- # Command template.
- cmd = 'pcs resource %(command)s %(resource_id)s %(type)s %(options)s'
- # Process operations.
- if module.params.has_key('operations'):
- cmd += ' %(operations)s'
- operations = []
- for op in module.params['operations']:
- op['options'] = ' '.join(['%s="%s"' % (key, value) for (key, value) in op['options'].items()])
- operations.append('op %(action)s %(options)s' % op)
- module.params['operations'] = ' '.join(operations)
-
- elif module.params['command'] == 'master':
- if not module.params.has_key('options'):
- module.fail_json(msg="missing required arguments: options.")
- if not module.params.has_key('ms_name'):
- module.fail_json(msg="missing required arguments: ms_name.")
- # Command template.
- cmd = 'pcs resource %(command)s %(name)s %(ms_name)s %(options)s'
-
- # Process options.
- if module.params.has_key('options'):
- options = module.params['options']
- if options:
- options = ' '.join(['%s="%s"' % (key, value) for (key, value) in options.items()])
- module.params['options'] = options
-
- if module.params.has_key('group'):
- if module.params['group']:
- cmd += ' --group ' + module.params['group']
-
- if module.params.has_key('disabled'):
- if module.params['disabled']:
- cmd += ' --disabled'
-
- # Run command.
- cmd = cmd % module.params
- message = 'Running cmd: %s' % cmd
- rc, out, err = module.run_command(cmd)
- if rc is 1:
- module.fail_json(msg="Execution failed.\nCommand: `%s`\nError: %s" % (cmd, err))
-
- module.exit_json(changed=True, msg=message)
-
-# import module snippets
-from ansible.module_utils.basic import *
-main()
-
diff --git a/library/pcs_resource.py b/library/pcs_resource.py
new file mode 100644
index 0000000..979014b
--- /dev/null
+++ b/library/pcs_resource.py
@@ -0,0 +1,501 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_resource
+short_description: "wrapper module for 'pcs resource' "
+description:
+ - "Module for creating, deleting and updating clusters resources using 'pcs' utility."
+ - "This module should be executed for same resorce only on one of the nodes in cluster at a time."
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that cluster resource exists"
+ - "'absent' - ensure cluster resource doesn't exist"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ name:
+ description:
+ - "name of cluster resource - cluster resource identifier"
+ required: true
+ type: str
+ resource_class:
+ description:
+ - class of cluster resource
+ required: false
+ default: 'ocf'
+ choices: ['ocf', 'systemd', 'stonith', 'master', 'promotable']
+ type: str
+ resource_type:
+ description:
+ - cluster resource type
+ required: false
+ type: str
+ options:
+ description:
+ - "additional options passed to 'pcs' command"
+ required: false
+ type: str
+ force_resource_update:
+ description:
+ - "skip checking for cluster changes when updating existing resource configuration
+ - use 'scope=resources' when pushing the change to cluster. Useful in busy clusters,
+ dangerous when there are concurent updates as they can be lost."
+ required: false
+ default: no
+ type: bool
+ cib_file:
+ description:
+ - "Apply changes to specified file containing cluster CIB instead of running cluster."
+ - "This module requires the file to already contain cluster configuration."
+ required: false
+ type: str
+ child_name:
+ description:
+ - "define custom name of child resource when creating multistate resource ('master' or 'promotable' resource_class)."
+ - "If not specified then the child resource name will have for of name+'-child'."
+ required: false
+ type: str
+ ignored_meta_attributes:
+ description:
+ - "list of meta attributes that will be ignored when comparing existing resources"
+ required: false
+ default: []
+ type: list
+ elements: str
+notes:
+ - tested on CentOS 6.8, 7.3
+ - module can create and delete clones, groups and master resources indirectly -
+ resource can specify --clone, --group, --master option which will cause them to create
+ or become part of clone/group/master
+'''
+
+EXAMPLES = '''
+- name: ensure Dummy('ocf:pacemaker:Dummy') resource with name 'test' is present
+ pcs_resource:
+ name: 'test'
+ resource_type: 'ocf:pacemaker:Dummy'
+
+- name: create 'stonith' class resource 'kdump' of type 'fence_kdump'
+ pcs_resource:
+ name: 'kdump'
+ resource_type: 'fence_kdump'
+ resource_class: 'stonith'
+
+- name: ensure that resource with name 'vip' is not present
+ pcs_resource:
+ name: 'vip'
+ state: 'absent'
+
+- name: ensure resource 'test2' of IPaddr2('ocf:heartbeat:IPaddr2') type exists an has 5 second monitor interval
+ pcs_resource:
+ name: 'test2'
+ resource_type: 'ocf:heartbeat:IPaddr2'
+ options: 'ip=192.168.1.2 op monitor interval=5'
+
+- name: create resource in group 'testgrp'
+ pcs_resource:
+ name: 'test3'
+ resource_type: 'ocf:pacemaker:Dummy'
+ options: '--group testgrp'
+
+- name: create multistate (Master/Slave) resource 'test' of 'ocf:pacemaker:Stateful' type - pcs-0.9
+ pcs_resource:
+ name: 'test'
+ resource_type: 'ocf:pacemaker:Stateful'
+ resource_class: 'master'
+ options: >
+ fake=some_value --master meta master-max=1 master-node-max=1 clone-max=2 clone-node-max=1 notify=true
+ op monitor interval=60s meta resource-stickiness=100
+
+- name: create multistate (Promotable) resource 'test' of 'ocf:pacemaker:Stateful' type - pcs-0.10
+ pcs_resource:
+ name: 'test'
+ resource_type: 'ocf:pacemaker:Stateful'
+ resource_class: 'promotable'
+ options: >
+ fake=some_value promotable meta promotable-max=1 promotable-node-max=1 clone-max=2 clone-node-max=1 notify=true
+ op monitor interval=60s meta resource-stickiness=100
+
+- name: ensure Dummy('ocf:pacemaker:Dummy') resource with name 'test' is present, but ignore if it is enabled or disabled (ignore target-role)
+ pcs_resource:
+ name: 'test'
+ resource_type: 'ocf:pacemaker:Dummy'
+ ignored_meta_attributes: [ 'target-role' ]
+'''
+
+# TODO if group exists and is not part of group, then specifying group won't put it into group
+# same problem is with clone and master - it might be better to make this functionality into separate module
+
+import sys
+import os.path
+import xml.etree.ElementTree as ET
+import tempfile
+import re
+from distutils.spawn import find_executable
+from ansible.module_utils.basic import AnsibleModule
+
+# determine if we have 'to_native' function that we can use for 'ansible --diff' output
+to_native_support = False
+try:
+ from ansible.module_utils._text import to_native
+ to_native_support = True
+except ImportError:
+ pass
+
+
+def replace_element(elem, replacement):
+ elem.clear()
+ elem.text = replacement.text
+ elem.tail = replacement.tail
+ elem.tag = replacement.tag
+ elem.attrib = replacement.attrib
+ elem[:] = replacement[:]
+
+
+def compare_resources(module, res1, res2):
+ # we now have 2 nodes that we can compare, so lets dump them into files for comparring
+ n1_file_fd, n1_tmp_path = tempfile.mkstemp()
+ n2_file_fd, n2_tmp_path = tempfile.mkstemp()
+ n1_file = open(n1_tmp_path, 'w')
+ n2_file = open(n2_tmp_path, 'w')
+ # dump the XML resource definitions into temporary files
+ sys.stdout = n1_file
+ ET.dump(res1)
+ sys.stdout = n2_file
+ ET.dump(res2)
+ sys.stdout = sys.__stdout__
+ # close files
+ n1_file.close()
+ n2_file.close()
+ # normalize the files and store results in new files - this also removes some unimportant spaces and stuff
+ n3_file_fd, n3_tmp_path = tempfile.mkstemp()
+ n4_file_fd, n4_tmp_path = tempfile.mkstemp()
+ rc, out, err = module.run_command('xmllint --format --output ' + n3_tmp_path + ' ' + n1_tmp_path)
+ rc, out, err = module.run_command('xmllint --format --output ' + n4_tmp_path + ' ' + n2_tmp_path)
+
+ # add files that should be cleaned up
+ module.add_cleanup_file(n1_tmp_path)
+ module.add_cleanup_file(n2_tmp_path)
+ module.add_cleanup_file(n3_tmp_path)
+ module.add_cleanup_file(n4_tmp_path)
+
+ # now compare files
+ diff = ''
+ rc, out, err = module.run_command('diff ' + n3_tmp_path + ' ' + n4_tmp_path)
+ if rc != 0:
+ # if there was difference then show the diff
+ n3_file = open(n3_tmp_path, 'r+')
+ n4_file = open(n4_tmp_path, 'r+')
+ if to_native_support:
+ # produce diff only where we have to_native function which give sensible output
+ # without 'to_native' whole text is wrapped as single line and not diffed
+ # seems that to_native was added in ansible-2.2 (commit 57701d7)
+ diff = {
+ 'before_header': '',
+ 'before': to_native(''.join(n3_file.readlines())),
+ 'after_header': '',
+ 'after': to_native(''.join(n4_file.readlines())),
+ }
+ return rc, diff
+
+
+def find_resource(cib, resource_id):
+ my_resource = None
+ tags = ['group', 'clone', 'master', 'primitive']
+ for elem in list(cib):
+ if elem.attrib.get('id') == resource_id:
+ return elem
+ elif elem.tag in tags:
+ my_resource = find_resource(elem, resource_id)
+ if my_resource is not None:
+ break
+ return my_resource
+
+
+def rename_multistate_element(multistate_resource, resource_name, child_name, resource_suffix):
+ multistate_resource.set('id', resource_name)
+ # search for meta_attributes tag
+ for elem in list(multistate_resource):
+ if elem.tag == 'meta_attributes':
+ new_meta_id = re.sub('^' + child_name + resource_suffix, resource_name, elem.attrib.get('id'))
+ elem.set('id', new_meta_id)
+ # replace ID of all nvpairs inside of this meta_attributes
+ for nvpair in list(elem):
+ new_nvpair_id = re.sub('^' + child_name + resource_suffix, resource_name, nvpair.attrib.get('id'))
+ nvpair.set('id', new_nvpair_id)
+
+
+def remove_ignored_meta_attributes(resource, ignored_meta_attributes):
+ for elem in list(resource):
+ if elem.tag == 'meta_attributes' and len(list(elem)) > 0:
+ for nvpair in list(elem):
+ if nvpair.tag == 'nvpair' and nvpair.attrib.get('name') in ignored_meta_attributes:
+ elem.remove(nvpair)
+
+
+def remove_empty_meta_attributes_tag(resource):
+ # remove the meta_attribute element to make comparison clean - Issue #10
+ # some versions of 'pcs' left empty 'meta_attributes' tag after 'pcs resource enable'
+ for elem in list(resource):
+ if elem.tag == 'meta_attributes' and len(list(elem)) == 0:
+ resource.remove(elem)
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ name=dict(required=True),
+ resource_class=dict(default="ocf", choices=['ocf', 'systemd', 'stonith', 'master', 'promotable']),
+ resource_type=dict(required=False),
+ options=dict(default="", required=False),
+ force_resource_update=dict(default=False, type='bool', required=False),
+ cib_file=dict(required=False),
+ child_name=dict(required=False),
+ ignored_meta_attributes=dict(required=False, type='list', elements='str', default=[]),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ resource_name = module.params['name']
+ resource_class = module.params['resource_class']
+ cib_file = module.params['cib_file']
+ if 'child_name' in module.params and module.params['child_name'] is None:
+ module.params['child_name'] = resource_name + '-child'
+ child_name = module.params['child_name']
+ resource_options = module.params['options']
+ ignored_meta_attributes = module.params['ignored_meta_attributes']
+
+ if state == 'present' and (not module.params['resource_type']):
+ module.fail_json(msg='When creating cluster resource you must specify the resource_type')
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ # get the pcs major.minor version
+ rc, out, err = module.run_command('pcs --version')
+ if rc == 0:
+ pcs_version = out.split('.')[0] + '.' + out.split('.')[1]
+ else:
+ module.fail_json(msg="pcs --version exited with non-zero exit code (" + rc + "): " + out + err)
+
+ # check if 'master' and 'promotable' classes have the needed keyword in options
+ if resource_class == 'master' and not ('--master' in resource_options or 'master' in resource_options):
+ module.fail_json(msg='When creating Master/Slave resource you must specify keyword "master" or "--master" in "options"')
+ if resource_class == 'promotable' and 'promotable' not in resource_options:
+ module.fail_json(msg='When creating promotable resource you must specify keyword "promotable" in "options"')
+
+ module.params['cib_file_param'] = ''
+ if cib_file is not None:
+ # use cib_file if specified
+ if os.path.isfile(cib_file):
+ try:
+ current_cib = ET.parse(cib_file)
+ except Exception as e:
+ module.fail_json(msg="Error encountered parsing the cib_file - %s" % (e))
+ current_cib_root = current_cib.getroot()
+ module.params['cib_file_param'] = '-f ' + cib_file
+ else:
+ module.fail_json(msg="%(cib_file)s is not a file or doesn't exists" % module.params)
+ else:
+ # get running cluster configuration
+ rc, out, err = module.run_command('pcs cluster cib')
+ if rc == 0:
+ current_cib_root = ET.fromstring(out)
+ else:
+ module.fail_json(msg='Failed to load cluster configuration', out=out, error=err)
+
+ # try to find the resource that we seek
+ resource = None
+ cib_resources = current_cib_root.find('./configuration/resources')
+ resource = find_resource(cib_resources, resource_name)
+
+ if state == 'present' and resource is None:
+ # resource should be present, but we don't see it in configuration - lets create it
+ result['changed'] = True
+ if not module.check_mode:
+ if resource_class == 'stonith':
+ cmd = 'pcs %(cib_file_param)s stonith create %(name)s %(resource_type)s %(options)s' % module.params
+ elif resource_class == 'master' or resource_class == 'promotable':
+ # we first create Master/Slave or Promotable resource with child_name and later rename it
+ cmd = 'pcs %(cib_file_param)s resource create %(child_name)s %(resource_type)s %(options)s' % module.params
+ else:
+ cmd = 'pcs %(cib_file_param)s resource create %(name)s %(resource_type)s %(options)s' % module.params
+ rc, out, err = module.run_command(cmd)
+ if rc != 0 and "Call cib_replace failed (-62): Timer expired" in err:
+ # EL6: special retry when we failed to create resource because of timer waiting on cib expired
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ if resource_class == 'master' or resource_class == 'promotable':
+ # rename the resource to desirable name
+ rc, out, err = module.run_command('pcs cluster cib')
+ if rc == 0:
+ updated_cib_root = ET.fromstring(out)
+ multistate_resource = None
+ updated_cib_resources = updated_cib_root.find('./configuration/resources')
+ resource_suffix = '-master' if pcs_version == '0.9' else '-clone'
+ multistate_resource = find_resource(updated_cib_resources, child_name + resource_suffix)
+ if multistate_resource is not None:
+ rename_multistate_element(multistate_resource, resource_name, child_name, resource_suffix)
+ ##
+ # when not using cib_file then we continue preparing changes for cib-push into running cluster
+ new_cib = ET.ElementTree(updated_cib_root)
+ new_cib_fd, new_cib_path = tempfile.mkstemp()
+ module.add_cleanup_file(new_cib_path)
+ new_cib.write(new_cib_path)
+ push_scope = 'scope=resources' if module.params['force_resource_update'] else ''
+ push_cmd = 'pcs cluster cib-push --config ' + push_scope + ' ' + new_cib_path
+ rc, out, err = module.run_command(push_cmd)
+ if rc == 0:
+ module.exit_json(changed=True)
+ else:
+ # rollback the failed rename by deleting the multistate resource
+ cmd = 'pcs %(cib_file_param)s resource delete %(child_name)s' % module.params
+ rc2, out2, err2 = module.run_command(cmd)
+ if rc2 == 0:
+ module.fail_json(msg="Failed to push updated configuration for multistate resource to cluster using command '" + push_cmd +
+ "'. Creation of multistate resource was rolled back. You can retry this task with " +
+ "'force_resource_update=true' to see if that helps.", output=out, error=err)
+ else:
+ module.fail_json(msg="Failed to delete resource after unsuccessful multistate resource configuration update using command '"
+ + cmd + "'", output=out2, error=err2)
+ else:
+ module.fail_json(msg="Failed to detect multistate resource after creating it with cmd '" + cmd + "'!",
+ output=out, error=err, previous_cib=current_cib)
+ module.exit_json(changed=True)
+ else:
+ module.fail_json(msg="Failed to create resource using command '" + cmd + "'", output=out, error=err)
+
+ elif state == 'present' and resource is not None:
+ # resource should be present and we have find resource with such ID - lets compare it with definition if it needs a change
+
+ # lets simulate how the resource would look like if it was created using command we have
+ clean_cib_fd, clean_cib_path = tempfile.mkstemp()
+ module.add_cleanup_file(clean_cib_path)
+ module.do_cleanup_files()
+ # we must be sure that clean_cib_path is empty
+ if resource_class == 'stonith':
+ cmd = 'pcs -f ' + clean_cib_path + ' stonith create %(name)s %(resource_type)s %(options)s' % module.params
+ elif resource_class == 'master' or resource_class == 'promotable':
+ # we first create Master/Slave or Promotable resource with child_name and later rename it
+ cmd = 'pcs -f ' + clean_cib_path + ' resource create %(child_name)s %(resource_type)s %(options)s' % module.params
+ else:
+ cmd = 'pcs -f ' + clean_cib_path + ' resource create %(name)s %(resource_type)s %(options)s' % module.params
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ if resource_class == 'master' or resource_class == 'promotable':
+ # deal with multistate resources
+ clean_cib = ET.parse(clean_cib_path)
+ clean_cib_root = clean_cib.getroot()
+ multistate_resource = None
+ updated_cib_resources = clean_cib_root.find('./configuration/resources')
+ resource_suffix = '-master' if pcs_version == '0.9' else '-clone'
+ multistate_resource = find_resource(updated_cib_resources, child_name + resource_suffix)
+ if multistate_resource is not None:
+ rename_multistate_element(multistate_resource, resource_name, child_name, resource_suffix)
+ # we try to write the changes into temporary cib_file
+ try:
+ clean_cib.write(clean_cib_path)
+ except Exception as e:
+ module.fail_json(msg="Error encountered writing intermediate multistate result to clean_cib_path - %s" % (e))
+ else:
+ module.fail_json(msg="Failed to detect intermediate multistate resource after creating it with cmd '" + cmd + "'!",
+ output=out, error=err, previous_cib=current_cib)
+
+ # we have a comparable resource created in clean cluster, so lets select it and compare it
+ clean_cib = ET.parse(clean_cib_path)
+ clean_cib_root = clean_cib.getroot()
+ clean_resource = None
+ cib_clean_resources = clean_cib_root.find('./configuration/resources')
+ clean_resource = find_resource(cib_clean_resources, resource_name)
+
+ if clean_resource is not None:
+ # cleanup the definition of resource and clean_resource before comparison
+ remove_ignored_meta_attributes(resource, ignored_meta_attributes)
+ remove_empty_meta_attributes_tag(resource)
+
+ remove_ignored_meta_attributes(clean_resource, ignored_meta_attributes)
+ remove_empty_meta_attributes_tag(clean_resource)
+
+ # compare the existing resource in cluster and simulated clean_resource
+ rc, diff = compare_resources(module, resource, clean_resource)
+ if rc == 0:
+ # if no differnces were find there is no need to update the resource
+ module.exit_json(changed=False)
+ else:
+ # otherwise lets replace the resource with new one
+ result['changed'] = True
+ result['diff'] = diff
+ if not module.check_mode:
+ replace_element(resource, clean_resource)
+ # when we use cib_file then we can dump the changed CIB directly into file
+ if cib_file is not None:
+ try:
+ current_cib.write(cib_file) # FIXME add try/catch for writing into file
+ except Exception as e:
+ module.fail_json(msg="Error encountered writing result to cib_file - %s" % (e))
+ module.exit_json(changed=True)
+ # when not using cib_file then we continue preparing changes for cib-push into running cluster
+ new_cib = ET.ElementTree(current_cib_root)
+ new_cib_fd, new_cib_path = tempfile.mkstemp()
+ module.add_cleanup_file(new_cib_path)
+ new_cib.write(new_cib_path)
+ push_scope = 'scope=resources' if module.params['force_resource_update'] else ''
+ push_cmd = 'pcs cluster cib-push ' + push_scope + ' ' + new_cib_path
+ rc, out, err = module.run_command(push_cmd)
+ if rc == 0:
+ module.exit_json(changed=True)
+ else:
+ module.fail_json(msg="Failed to push updated configuration to cluster using command '" + push_cmd + "'", output=out, error=err)
+ else:
+ module.fail_json(msg="Unable to find simulated resource, This is most probably a bug.")
+ else:
+ module.fail_json(msg="Unable to simulate resource with given definition using command '" + cmd + "'", output=out, error=err)
+
+ elif state == 'absent' and resource is not None:
+ # resource should not be present but we have found something - lets remove that
+ result['changed'] = True
+ if not module.check_mode:
+ if resource_class == 'stonith':
+ cmd = 'pcs %(cib_file_param)s stonith delete %(name)s' % module.params
+ else:
+ cmd = 'pcs %(cib_file_param)s resource delete %(name)s' % module.params
+ rc, out, err = module.run_command(cmd)
+ if rc == 0:
+ module.exit_json(changed=True)
+ else:
+ module.fail_json(msg="Failed to delete resource using command '" + cmd + "'", output=out, error=err)
+
+ else:
+ # resource should not be present and is nto there, nothing to do
+ result['changed'] = False
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_resource_defaults.py b/library/pcs_resource_defaults.py
new file mode 100644
index 0000000..bc3c883
--- /dev/null
+++ b/library/pcs_resource_defaults.py
@@ -0,0 +1,187 @@
+#!/usr/bin/python
+# Copyright: (c) 2018, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_resource_defaults
+short_description: "wrapper module for 'pcs resource defaults' and 'pcs resource op defaults'"
+description:
+ - "module for setting and unsetting clusters resource deafults and resource operation defaults using 'pcs' utility"
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that resource default exists with given value"
+ - "'absent' - ensure resource default doesn't exist (is unset)"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ defaults_type:
+ description:
+ - "'meta' - resource meta defaults, 'pcs resource defaults ...'"
+ - "'op' - resource operation defaults, 'pcs resource op defaults ...'"
+ required: false
+ default: meta
+ choices: ['meta', 'op']
+ type: str
+ name:
+ description:
+ - name of cluster resource default
+ required: true
+ type: str
+ value:
+ description:
+ - value of cluster resource default
+ required: false
+ type: str
+ cib_file:
+ description:
+ - "Apply changes to specified file containing cluster CIB instead of running cluster."
+ required: false
+ type: str
+notes:
+ - tested on CentOS 6.10 - pcs 0.9.155
+ - tested on CentOS 7.9 - pcs 0.9.169
+ - tested on CentOS 8.2 - pcs 0.10.4
+ - tested on Fedora 32 - pcs 0.10.7
+'''
+
+EXAMPLES = '''
+- name: set resource-stickiness=100 to be default for resources
+ pcs_resource_defaults:
+ name: 'resource-stickiness'
+ value: '100'
+
+- name: remove the 'resource-stickiness' resource default
+ pcs_resource_defaults:
+ name: 'resource-stickiness'
+ state: 'absent'
+
+- name: set default operation timeout for resources to 60
+ pcs_resource_defaults:
+ defaults_type: 'op'
+ name: 'timeout'
+ value: '60'
+
+- name: remove the custom default operation timeout
+ pcs_resource_defaults:
+ defaults_type: 'op'
+ name: 'timeout'
+ state: 'absent'
+'''
+
+import os.path
+from distutils.spawn import find_executable
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ defaults_type=dict(required=False, default="meta", choices=['meta', 'op']),
+ name=dict(required=True),
+ value=dict(required=False),
+ cib_file=dict(required=False),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ name = module.params['name']
+ defaults_type = module.params['defaults_type']
+ value = module.params['value']
+ cib_file = module.params['cib_file']
+
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ if state == 'present' and value is None:
+ module.fail_json(msg="To set a defaults 'value' must be specified.")
+
+ module.params['cib_file_param'] = ''
+ if cib_file is not None and os.path.isfile(cib_file):
+ module.params['cib_file_param'] = '-f ' + cib_file
+
+ # get defaults list from running cluster
+ if defaults_type == 'meta':
+ rc, out, err = module.run_command('pcs %(cib_file_param)s resource defaults' % module.params)
+ elif defaults_type == 'op':
+ rc, out, err = module.run_command('pcs %(cib_file_param)s resource op defaults' % module.params)
+ else:
+ module.fail_json(msg="'" + defaults_type + "' is not implemented by this module")
+
+ defaults = {}
+ if rc == 0:
+ for row in out.split('\n')[:-1]:
+ if row == 'No defaults set':
+ break
+ if row == 'Meta Attrs: rsc_defaults-options' or row == 'Meta Attrs: op_defaults-options':
+ continue
+ tmp = row.split(':') if ':' in row else row.split('=')
+ defaults[tmp[0].strip()] = tmp[1].lstrip()
+ else:
+ module.fail_json(msg='Failed to load resource defaults from cluster. Is cluster running?')
+
+ result['detected_defaults'] = defaults
+
+ if state == 'present' and (name not in defaults or defaults[name] != value):
+ # default not found or having a different value
+ result['changed'] = True
+ if not module.check_mode:
+ if defaults_type == 'meta':
+ cmd_set = 'pcs %(cib_file_param)s resource defaults %(name)s=%(value)s' % module.params
+ elif defaults_type == 'op':
+ cmd_set = 'pcs %(cib_file_param)s resource op defaults %(name)s=%(value)s' % module.params
+ else:
+ module.fail_json(msg="'" + defaults_type + "' is not implemented by this module")
+ rc, out, err = module.run_command(cmd_set)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to set " + defaults_type + " with cmd : '" + cmd_set + "'", output=out, error=err)
+
+ elif state == 'absent' and name in defaults:
+ # default found but it should not be set
+ result['changed'] = True
+ if not module.check_mode:
+ if defaults_type == 'meta':
+ cmd_unset = 'pcs %(cib_file_param)s resource defaults %(name)s=' % module.params
+ elif defaults_type == 'op':
+ cmd_unset = 'pcs %(cib_file_param)s resource op defaults %(name)s=' % module.params
+ else:
+ module.fail_json(msg="'" + defaults_type + "' is not implemented by this module")
+ rc, out, err = module.run_command(cmd_unset)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to unset " + defaults_type + " default with cmd: '" + cmd_unset + "'", output=out, error=err)
+ else:
+ # No change needed
+ result['changed'] = False
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/library/pcs_stonith_level.py b/library/pcs_stonith_level.py
new file mode 100644
index 0000000..b15a828
--- /dev/null
+++ b/library/pcs_stonith_level.py
@@ -0,0 +1,186 @@
+#!/usr/bin/python
+# Copyright: (c) 2021, Ondrej Famera
+# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
+# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {
+ 'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'
+}
+
+DOCUMENTATION = '''
+---
+author: "Ondrej Famera (@OndrejHome)"
+module: pcs_stonith_level
+short_description: "wrapper module for 'pcs stonith level'"
+description:
+ - "module for creating and deleting stonith levels using 'pcs' utility"
+version_added: "2.4"
+options:
+ state:
+ description:
+ - "'present' - ensure that stonith level for given node and stonith device exists"
+ - "'absent' - ensure that stonith level for given node and stonith device doesn't exist"
+ required: false
+ default: present
+ choices: ['present', 'absent']
+ type: str
+ level:
+ description:
+ - numerical stonith level (1-9)
+ required: true
+ choices: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ type: int
+ node_name:
+ description:
+ - name of cluster node for this stonith level and stonith_device
+ required: true
+ type: str
+ stonith_device:
+ description:
+ - name of existing stonith device
+ required: true
+ type: str
+ cib_file:
+ description:
+ - "Apply changes to specified file containing cluster CIB instead of running cluster."
+ - "This module requires the file to already contain cluster configuration."
+ required: false
+ type: str
+notes:
+ - when deleting the stonith level only exact match is being deleted - same behaviour as pcs
+ - tested on CentOS 7.9/8.3
+'''
+
+EXAMPLES = '''
+- name: add fence-kdump as level 1 stonith device for node-a
+ pcs_stonith_level:
+ level: '1'
+ node_name: 'node-a'
+ stonith_device: 'fence_kdump'
+
+- name: remove fence-xvm level 2 stonith device from node-b
+ pcs_stonith_level:
+ level: '2'
+ node_name: 'node-b'
+ stonith_device: 'fence_xvm'
+ state: 'absent'
+'''
+
+import os.path
+import xml.etree.ElementTree as ET
+from distutils.spawn import find_executable
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+def run_module():
+ module = AnsibleModule(
+ argument_spec=dict(
+ state=dict(default="present", choices=['present', 'absent']),
+ level=dict(required=True, type='int', choices=[1, 2, 3, 4, 5, 6, 7, 8, 9]),
+ node_name=dict(required=True, type='str'),
+ stonith_device=dict(required=True, type='str'),
+ cib_file=dict(required=False),
+ ),
+ supports_check_mode=True
+ )
+
+ state = module.params['state']
+ level = module.params['level']
+ node_name = module.params['node_name']
+ stonith_device = module.params['stonith_device']
+ cib_file = module.params['cib_file']
+
+ result = {}
+
+ if find_executable('pcs') is None:
+ module.fail_json(msg="'pcs' executable not found. Install 'pcs'.")
+
+ module.params['cib_file_param'] = ''
+ if cib_file is not None:
+ # use cib_file if specified
+ if os.path.isfile(cib_file):
+ try:
+ current_cib = ET.parse(cib_file)
+ except Exception as e:
+ module.fail_json(msg="Error encountered parsing the cib_file - %s" % (e))
+ current_cib_root = current_cib.getroot()
+ module.params['cib_file_param'] = '-f ' + cib_file
+ else:
+ module.fail_json(msg="%(cib_file)s is not a file or doesn't exists" % module.params)
+ else:
+ # get running cluster configuration
+ rc, out, err = module.run_command('pcs cluster cib')
+ if rc == 0:
+ current_cib_root = ET.fromstring(out)
+ else:
+ module.fail_json(msg='Failed to load cluster configuration', out=out, error=err)
+
+ # try to find the fencing-level
+ fencing_level = None
+ fencing_levels = current_cib_root.findall("./configuration/fencing-topology/fencing-level")
+ for flevel in fencing_levels:
+ # level must match all criteria (level, node_name, stonith_device)
+ if (flevel.attrib.get('index') == str(level)
+ and flevel.attrib.get('target') == node_name
+ and flevel.attrib.get('devices') == stonith_device):
+ fencing_level = flevel
+ break
+
+ if fencing_level is not None:
+ result.update({
+ 'fence_level_was_matched': True,
+ 'level': None if fencing_level is None else fencing_level.attrib.get('index'),
+ 'node_name': None if fencing_level is None else fencing_level.attrib.get('target'),
+ 'devices': None if fencing_level is None else fencing_level.attrib.get('devices'),
+ 'fence_level_id': None if fencing_level is None else fencing_level.attrib.get('id'),
+ })
+ else:
+ result.update({'fence_level_was_matched': False})
+
+ # commands for creating/deleting stonith levels
+ cmd_create = 'pcs %(cib_file_param)s stonith level add %(level)s %(node_name)s %(stonith_device)s' % module.params
+ cmd_delete = 'pcs %(cib_file_param)s stonith level remove %(level)s %(node_name)s %(stonith_device)s' % module.params
+
+ if state == 'present' and fencing_level is None:
+ # stonith level should be present, but we don't see it in configuration - lets create it
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_create)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to create stonith level with cmd: '" + cmd_create + "'", output=out, error=err)
+
+ elif state == 'present' and fencing_level is not None:
+ # stonith level should be present and it is there, nothing to do
+ result['changed'] = False
+
+ elif state == 'absent' and fencing_level is not None:
+ # stonith level should not be present but we have found something - lets remove that
+ result['changed'] = True
+ if not module.check_mode:
+ rc, out, err = module.run_command(cmd_delete)
+ if rc == 0:
+ module.exit_json(**result)
+ else:
+ module.fail_json(msg="Failed to delete stonith level with cmd: '" + cmd_delete + "'", output=out, error=err)
+ else:
+ # stonith level should not be present and is not there, nothing to do
+ result['changed'] = False
+
+ # END of module
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tasks/paf.yml b/tasks/paf.yml
index 60d1e1c..df96358 100644
--- a/tasks/paf.yml
+++ b/tasks/paf.yml
@@ -3,7 +3,7 @@
- name: select proper PAF package (centos7)
set_fact:
paf_pkg: 'resource-agents-paf-{{ postgres_ha_paf_version }}-1.noarch.rpm'
- when: os_version == 'centos7'
+ when: (os_version == 'centos7' or os_version == 'centos8')
- name: select proper PAF package (centos6)
set_fact:
@@ -22,6 +22,7 @@
yum:
name: "/tmp/{{ paf_pkg }}"
state: present
+ disable_gpg_check: True
- name: apply PAF v2.2.0 fix for newest pacemaker
copy:
@@ -44,61 +45,52 @@
mode: 0555
when: postgres_ha_paf_geo_patch
-- name: prepare DB recovery config
+- name: prepare DB recovery.conf
template: src=recovery.conf.pcmk.j2 dest="{{ postgres_ha_pg_data }}/../recovery.conf.{{postgres_ha_cluster_name}}.pcmk"
args:
owner: postgres
group: postgres
mode: 0644
+ when: postgres_ha_pg_version | int < 12
- name: stop database for clustering
service: name="{{ postgres_ha_pg_systemd_svcname }}" state=stopped enabled=false
-- name: create database cluster resource
- when: inventory_hostname == postgres_ha_cluster_master_host # run only on one node
- pcs_resource: command=create resource_id="{{ postgres_ha_cluster_pg_res_name }}" type=ocf:heartbeat:pgsqlms
- args:
- disabled: True
- options:
- bindir: "{{ postgres_ha_pg_bindir }}"
- pgdata: "{{ postgres_ha_pg_data }}"
- pgport: "{{ postgres_ha_pg_port }}"
- recovery_template: "{{ postgres_ha_pg_data }}/../recovery.conf.{{postgres_ha_cluster_name}}.pcmk"
- operations:
- - action: start
- options:
- timeout: 60s
- - action: stop
- options:
- timeout: 60s
- - action: promote
- options:
- timeout: 30s
- - action: demote
- options:
- timeout: 120s
- - action: notify
- options:
- timeout: 60s
- - action: monitor
- options:
- interval: "{{ postgres_ha_monitor_interval_pgmaster }}"
- timeout: 10s
- role: Master
- - action: monitor
- options:
- interval: "{{ postgres_ha_monitor_interval_pgslave }}"
- timeout: 10s
- role: Slave
+- name: remove primary_conninfo from postgresql.auto.conf
+ lineinfile:
+ dest: "{{ postgres_ha_pg_data }}/postgresql.auto.conf"
+ regexp: "^primary_conninfo ="
+ state: absent
+ ignore_errors: True
-- name: create master DB resource
+# 'force_resource_update' is commented out because it might trigger database restart after role re-run
+- name: create database cluster resource
when: inventory_hostname == postgres_ha_cluster_master_host # run only on one node
- pcs_resource: command=master resource_id="{{ postgres_ha_cluster_pg_HA_res_name }}" ms_name="{{ postgres_ha_cluster_pg_res_name }}" disabled=True
- args:
- options:
- master-max : 1
- master-node-max : 1
- clone-max : "{{ ansible_play_batch|length }}"
- clone-node-max : 1
- notify : true
+ pcs_resource:
+ name: "{{ postgres_ha_cluster_pg_HA_res_name }}" # master resource name
+ child_name: "{{ postgres_ha_cluster_pg_res_name }}" # slave resource name
+ resource_class: '{% if ansible_distribution_major_version | int >= 8 %}promotable{% else %}master{% endif %}'
+ resource_type: ocf:heartbeat:pgsqlms
+ #force_resource_update: true
+ options: >
+ {% if db_resource_exists is not succeeded %}--disabled{% endif %}
+ bindir="{{ postgres_ha_pg_bindir }}"
+ pgdata="{{ postgres_ha_pg_data }}"
+ pgport="{{ postgres_ha_pg_port }}"
+ {% if postgres_ha_pg_version | int < 12 %}
+ recovery_template="{{ postgres_ha_pg_data }}/../recovery.conf.{{postgres_ha_cluster_name}}.pcmk"
+ {% endif %}
+ '{% if ansible_distribution_major_version | int >= 8 %}promotable{% else %}master{% endif %}'
+ master-max=1
+ master-node-max=1
+ clone-max="{{ ansible_play_batch|length }}"
+ clone-node-max=1
+ notify=true
+ op start timeout=60s
+ op stop timeout=60s
+ op promote timeout=30s
+ op demote timeout=120s
+ op notify timeout=60s
+ op monitor interval="{{ postgres_ha_monitor_interval_pgmaster }}" timeout=10s role="Master"
+ op monitor interval="{{ postgres_ha_monitor_interval_pgslave }}" timeout=10s role="Slave"
diff --git a/tasks/pcs.yml b/tasks/pcs.yml
index b85ec9a..0c738c1 100644
--- a/tasks/pcs.yml
+++ b/tasks/pcs.yml
@@ -3,6 +3,12 @@
- debug: msg='cluster_members={{ansible_play_batch}}'
run_once: true
+- name: enable HighAvailability dnf stream
+ command: dnf config-manager --set-enabled HighAvailability
+ args:
+ warn: false
+ when: os_version == 'centos8'
+
- name: install cluster pkgs
yum:
name: pcs
@@ -59,17 +65,19 @@
password: "{{ postgres_ha_cluster_ha_password_hash }}"
- name: setup cluster auth
- shell: pcs cluster auth {{ ansible_play_batch | join( " ") }} -u hacluster -p "{{ postgres_ha_cluster_ha_password }}"
+ shell: pcs "{% if os_version == 'centos8' %}host{% else %}cluster{% endif %}" auth {{ ansible_play_batch | join( " ") }} -u hacluster -p "{{ postgres_ha_cluster_ha_password }}"
+ retries: 15
+ delay: 2
# We create cluster in two steps:
# 1. create one-node cluster
# 2. join other cluster nodes (the task below)
# The reason is that we want to support adding new nodes by re-running the role.
-- name: create cluster (centos7)
- shell: pcs cluster setup --name {{ postgres_ha_cluster_name }} "{{ pcs_hostname }}" {% if postgres_ha_pcs_advanced_params %}{% for param in postgres_ha_pcs_advanced_params|difference(['addr0', 'addr1', 'addr2', 'addr3', 'transport']) %}--{{ param }} {{ postgres_ha_pcs_advanced_params[param] }} {% endfor %}{% endif %} {% if postgres_ha_mcast_enable %}--transport udp {{ pcs_ring_addrs }}{% endif %}
+- name: create cluster (centos7/8)
+ shell: pcs cluster setup {% if os_version == 'centos7' %}--name{% else %}--start{% endif %} {{ postgres_ha_cluster_name }} "{{ pcs_hostname }}" {% if postgres_ha_pcs_advanced_params %}{% for param in postgres_ha_pcs_advanced_params|difference(['addr0', 'addr1', 'addr2', 'addr3', 'transport']) %}--{{ param }} {{ postgres_ha_pcs_advanced_params[param] }} {% endfor %}{% endif %} {% if postgres_ha_mcast_enable %}--transport udp {{ pcs_ring_addrs }}{% endif %}
args:
creates: /etc/corosync/corosync.conf
- when: os_version == 'centos7' and
+ when: (os_version == 'centos7' or os_version == 'centos8') and
inventory_hostname == postgres_ha_cluster_master_host # run only on master node
# ignore these parameters from postgres_ha_pcs_advanced_params: 'addr0', 'addr1', 'addr2', 'addr3', 'transport'
@@ -80,10 +88,10 @@
when: os_version == 'centos6' and
inventory_hostname == postgres_ha_cluster_master_host # run only on master node
-- name: join cluster nodes (centos7)
+- name: join cluster nodes (centos7/8)
shell: /bin/sh -c "if ! grep -q 'ring0_addr[:] *{{ item }}[\t ]*$' /etc/corosync/corosync.conf; then pcs cluster node add {{ hostvars[item]['pcs_hostname'] }}; fi"
with_items: '{{ ansible_play_batch | difference([inventory_hostname]) }}' # all hosts except me
- when: os_version == 'centos7' and
+ when: (os_version == 'centos7' or os_version == 'centos8') and
inventory_hostname == postgres_ha_cluster_master_host # run only on master node
- name: join cluster nodes (centos6)
@@ -117,14 +125,21 @@
- name: alter cluster transition settings
pcs_property: name=crmd-transition-delay value=3s
run_once: true
+ when: (os_version == 'centos6' or os_version == 'centos7')
+
+#- name: alter cluster migration-threshold settings
+# pcs_resource_defaults: name=migration-threshold value=5
+# run_once: true
+# when: os_version == 'centos8'
- name: verify cluster configuration
shell: crm_verify -L -V
run_once: true
+ changed_when: false
- name: enable cluster autostart
shell: pcs cluster enable
-# reload corosync if neccessary (done automatically on the end of the tasklist)
-#- meta: flush_handlers
+# reload corosync if neccessary
+- meta: flush_handlers
diff --git a/tasks/postgresql_sync.yml b/tasks/postgresql_sync.yml
index ffcf661..f77a1d0 100644
--- a/tasks/postgresql_sync.yml
+++ b/tasks/postgresql_sync.yml
@@ -1,35 +1,22 @@
# vim: set filetype=yaml expandtab tabstop=2 shiftwidth=2 softtabstop=2 background=dark :
-# The name of the rpm file that imports the pg repo depends on the OS family and on the pg version.
-# This variable sets the last version digit of the repo file (e.g 9.6-3).
-- name: set pg repo rpm version suffix (v9.x)
- set_fact:
- pg_pkg_vers_suffix: '3'
-
-- name: set pg repo rpm version suffix for (v10+)
- set_fact:
- pg_pkg_vers_suffix: '2'
- when: postgres_ha_pg_version >= 10
-
-- name: determine the correct postgres package name (all systems)
- set_fact:
- pg_pkg_name: 'pgdg-centos{{ postgres_ha_pg_version | replace(".", "") }}-{{ postgres_ha_pg_version }}-{{ pg_pkg_vers_suffix }}.noarch.rpm'
- #when: ansible_distribution == 'CentOS' # this is default
-
-- name: determine the correct postgres package name (RHEL)
- set_fact:
- pg_pkg_name: 'pgdg-redhat{{ postgres_ha_pg_version | replace(".", "") }}-{{ postgres_ha_pg_version }}-{{ pg_pkg_vers_suffix }}.noarch.rpm'
- when: ansible_distribution == 'Red Hat Enterprise Linux'
+- name: disable dnf postgres module
+ command: dnf -qy module disable postgresql
+ args:
+ warn: false
+ when: os_version == 'centos8'
- name: 'import pg{{ postgres_ha_pg_version | replace(".", "") }} repo'
yum:
name: "{{ postgres_ha_repo_url }}"
state: installed
+ disable_gpg_check: True
when: postgres_ha_import_repo
- name: 'install pg{{ postgres_ha_pg_version | replace(".", "") }}'
yum:
- name: 'postgresql{{ postgres_ha_pg_version | replace(".", "") }}-server, postgresql{{ postgres_ha_pg_version | replace(".", "") }}-contrib, python-psycopg2'
+ name: 'postgresql{{ postgres_ha_pg_version | replace(".", "") }}-server, postgresql{{ postgres_ha_pg_version | replace(".", "") }}-contrib, python{% if ansible_distribution_major_version | int >= 8 %}3{% endif %}-psycopg2'
+ # purposely omited ansible_os_family == "RedHat" to simplify this task ^^
state: installed
- name: init DB dir on master if necessary (centos 7 and postgresql 9.6 or older)
@@ -38,7 +25,7 @@
creates: "{{ postgres_ha_pg_data }}/PG_VERSION"
# run only on one node
when: inventory_hostname == postgres_ha_cluster_master_host
- and os_version == 'centos7'
+ and (os_version == 'centos7' or os_version == 'centos8')
and postgres_ha_pg_version |int < 10
- name: init DB dir on master if necessary (centos 7 and postgresql 10 or above)
@@ -47,7 +34,7 @@
creates: "{{ postgres_ha_pg_data }}/PG_VERSION"
# run only on one node
when: inventory_hostname == postgres_ha_cluster_master_host
- and os_version == 'centos7'
+ and (os_version == 'centos7' or os_version == 'centos8')
and postgres_ha_pg_version |int >= 10
- name: init DB dir on master if necessary (centos 6)
@@ -72,7 +59,7 @@
# mode: 0600
- name: alter clustering-related settings in postgresql.conf
- replace:
+ replace:
dest="{{ postgres_ha_pg_data }}/postgresql.conf"
regexp="^([# ]*{{ item.key }} *=.*$)"
replace="{{ item.key }} = {{ item.value }}"
@@ -80,6 +67,18 @@
with_dict: "{{ postgres_ha_postgresql_conf_vars }}"
notify: restart postgresql
+- name: alter clustering-related settings in postgresql.conf (pg12+)
+ replace:
+ dest="{{ postgres_ha_pg_data }}/postgresql.conf"
+ regexp="^([# ]*{{ item.key }} *=.*$)"
+ replace="{{ item.key }} = {{ item.value }}"
+ with_dict: "{{ postgres_ha_postgresql_conf_vars_12 }}"
+ when: postgres_ha_pg_version | int >= 12 and
+ (inventory_hostname == postgres_ha_cluster_master_host or
+ db_prevsync_file.stat.exists)
+ # run on master and on already-synchronized nodes
+ notify: restart postgresql
+
- meta: flush_handlers
- name: alter DB ACL in pg_hba.conf
@@ -185,7 +184,7 @@
# if DB is clustered and is not running, we have a problem.. try at least cleaning the resource status
- name: start master DB if necessary (in cluster)
- shell: pcs resource cleanup "{{ postgres_ha_cluster_pg_HA_res_name }}" && sleep 15
+ shell: pcs resource manage "{{ postgres_ha_cluster_pg_HA_res_name }}" && pcs resource clear "{{ postgres_ha_cluster_pg_HA_res_name }}" && pcs resource refresh "{{ postgres_ha_cluster_pg_HA_res_name }}" && pcs resource enable "{{ postgres_ha_cluster_pg_HA_res_name }}" && sleep 20
when: (inventory_hostname == postgres_ha_cluster_master_host) and
(db_resource_exists is succeeded) and
(db_running is failed)
@@ -239,6 +238,16 @@
# (datadir_files.matched|int == 0)
register: slave_resync
+- name: reapply clustering-related settings in postgresql.conf (pg12+)
+ replace:
+ dest="{{ postgres_ha_pg_data }}/postgresql.conf"
+ regexp="^([# ]*{{ item.key }} *=.*$)"
+ replace="{{ item.key }} = {{ item.value }}"
+ with_dict: "{{ postgres_ha_postgresql_conf_vars_12 }}"
+ when: postgres_ha_pg_version | int >= 12 and
+ inventory_hostname != postgres_ha_cluster_master_host
+ # run on slaves
+
- name: forbid self-replication in pg_hba.conf on slaves
lineinfile: dest="{{ postgres_ha_pg_data }}/pg_hba.conf"
regexp='^host replication .*{{ hostvars[item].ansible_default_ipv4.address }}/32'
diff --git a/tasks/vip.yml b/tasks/vip.yml
index b6eb464..30a4408 100644
--- a/tasks/vip.yml
+++ b/tasks/vip.yml
@@ -2,14 +2,12 @@
- name: create virtual IP resource
when: inventory_hostname == postgres_ha_cluster_master_host # run only on one node
- pcs_resource: command=create resource_id="{{ postgres_ha_cluster_vip_res_name }}" type=ocf:heartbeat:IPaddr2
- args:
- options:
- ip: "{{ postgres_ha_cluster_vip }}"
- cidr_netmask: "{{ postgres_ha_cluster_vip_mask }}"
- operations:
- - action: monitor
- options:
- interval: 10s
+ pcs_resource:
+ name: "{{ postgres_ha_cluster_vip_res_name }}"
+ resource_type: ocf:heartbeat:IPaddr2
+ options: >
+ ip="{{ postgres_ha_cluster_vip }}"
+ cidr_netmask="{{ postgres_ha_cluster_vip_mask }}"
+ op monitor interval=10s