Init: mediaserver

This commit is contained in:
2023-02-08 12:13:28 +01:00
parent 848bc9739c
commit f7c23d4ba9
31914 changed files with 6175775 additions and 0 deletions

View File

@@ -0,0 +1,473 @@
================================
lowlydba.sqlserver Release Notes
================================
.. contents:: Topics
v1.3.1
======
Release Summary
---------------
Small bugfixes and documentation enhancements.
Minor Changes
-------------
- Update login module documentation to indicate result will always be changed when a password is supplied. (https://github.com/lowlydba/lowlydba.sqlserver/pull/167)
Bugfixes
--------
- Fixes to incorrect variable reference in Login module (https://github.com/lowlydba/lowlydba.sqlserver/pull/161)
v1.3.0
======
Release Summary
---------------
New module to manage credentials added!
Minor Changes
-------------
- Adding a new credential module
New Modules
-----------
- credential - Configures a credential on a SQL server
v1.2.1
======
Release Summary
---------------
More Azure SQL Managed Instance compatibility fixes.
Bugfixes
--------
- Added missing mapping for UseDestinationDefaultDirectories (https://github.com/lowlydba/lowlydba.sqlserver/pull/153)
- Removed default value for KeepCDC to fix compatability with SQL MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/153)
- Removed default value for UseDestinationDefaultDirectories to fix compatability with SQL MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/153)
v1.2.0
======
Release Summary
---------------
Azure SQL MI compatibility fixes & indicating required restarts for settings changes.
Minor Changes
-------------
- Fixed typo in the traceflag module's documentation. (https://github.com/lowlydba/lowlydba.sqlserver/pull/150)
- Return "RestartRequired" when a module performs changes that require an addition service restart to take effect. (https://github.com/lowlydba/lowlydba.sqlserver/pull/150/)
Bugfixes
--------
- Removed default value for ReplaceDbNameInFile to fix compatability with SQL MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/148)
v1.1.3
======
Release Summary
---------------
Another minor fix to increase SQL Managed Instance support.
Bugfixes
--------
- Removed default value for reuse_source_folder_structure to fix compatability with SQL MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/145)
v1.1.2
======
Release Summary
---------------
Bug fix for Azure Database Managed Instance compatibility.
Bugfixes
--------
- Removed the default value for xp_dirtree to allow compatibility with Azure SQL Mangaed instances (https://github.com/lowlydba/lowlydba.sqlserver/pull/141)
v1.1.1
======
Minor Changes
-------------
- modules - all modules now document their platform and support for check mode in their attributes documentation (https://github.com/lowlydba/lowlydba.sqlserver/pull/134).
v1.1.0
======
Release Summary
---------------
Adding a new user module.
New Modules
-----------
- user - Configures a user within a database
v1.0.4
======
Release Summary
---------------
Minor fixes to resolve new dlevel sanity checks.
Bugfixes
--------
- Fix cleanup_time default to match documentation default & lint fixes (https://github.com/lowlydba/lowlydba.sqlserver/pull/127).
v1.0.3
======
Release Summary
---------------
Minor documentation fixes from the second Ansible inclusion review.
Bugfixes
--------
- Minor documentation fixes (https://github.com/lowlydba/lowlydba.sqlserver/pull/122).
v1.0.2
======
Release Summary
---------------
Minor documentation bugfixes and enhancements as requested in the Ansible inclusion process.
Bugfixes
--------
- _SqlServerUtils module_util - added explicit license to private module util (https://github.com/lowlydba/lowlydba.sqlserver/pull/119).
- meta/runtime.yml - updated out of date runtime version info (https://github.com/lowlydba/lowlydba.sqlserver/pull/119).
- most modules - fixed alignment, formatting, and typos in module documentation (https://github.com/lowlydba/lowlydba.sqlserver/pull/119).
v1.0.1
======
Release Summary
---------------
Minor bug fix.
Bugfixes
--------
- Fixed bug in how the classifier function name is being assigned to the variable in the resource_governor module.
v1.0.0
======
Release Summary
---------------
Bumping to version 1.0.0 now that this collection is being used in production in at least one place 🎉
v0.11.2
=======
Release Summary
---------------
Bumping required dbatools version to ensure the `restore` module works on MacOS PowerShell Core (https://github.com/dataplat/dbatools/pull/8435).
v0.11.1
=======
Release Summary
---------------
Bug fixes for AlwaysOn related modules and fixing errors in some documentation examples.
Bugfixes
--------
- Fix `availability_group` module so that NUL backups can be properly taken if needed.
- Fix incorrect examples in `availability_group` module documentation.
- Fix incorrect examples in `install_script` module documentation.
- Fix incorrect examples in `spn` module documentationb.
- Fixed bugs where adding replica did not work properly for several reasons.
v0.11.0
=======
Release Summary
---------------
Adding new dbops module.
New Modules
-----------
- install_script - Runs migration scripts against a database.
v0.10.1
=======
Release Summary
---------------
Bug fix for resource_governor.
Bugfixes
--------
- Fix change detection in resource_governor module.
v0.10.0
=======
Release Summary
---------------
The first_responder_kit and tcp_port modules, along with a bump in the required dbatools version.
Minor Changes
-------------
- Update minimum required DBATools version universally to 1.1.108 to accommodate new tcp module.
New Modules
-----------
- first_responder_kit - Install/update the First Responder Kit scripts.
- tcp_port - Sets the TCP port for the instance.
v0.9.3
======
Release Summary
---------------
More change detection fixing.
Bugfixes
--------
- memory - Fix improper changed detection.
v0.9.2
======
Release Summary
---------------
Bugfixes for agent related modules that incorrectly reported change statuses.
Bugfixes
--------
- agent_job - Fix incorrectly reported change status when no change occurred.
- agent_job_schedule - Fix incorrectly reported change status when no change occurred.
- agent_job_step - Fix incorrectly reported change status when no change occurred.
v0.9.1
======
Release Summary
---------------
Bugfix!
Bugfixes
--------
- Allow agent job steps to be removed by specifying the step ID only. This is likely needed in cleanup of steps from previous job configurations.
v0.9.0
======
Bugfixes
--------
- backup - Only use blocksize when specified.
New Modules
-----------
- restore - Performs a restore operation.
v0.8.0
======
Release Summary
---------------
A few small fixes and the new 'backup' module.
Minor Changes
-------------
- Standardize use of 'database' vs 'database_name' in all documentation and options specs. Not a breaking change.
Bugfixes
--------
- Fix inability to enable an agent job schedule after it has been disabled.
New Modules
-----------
- backup - Performs a backup operation.
v0.7.0
======
Release Summary
---------------
Add module for DBA Multitool.
New Modules
-----------
- dba_multitool - Install/update the DBA Multitool suite by John McCAll
v0.6.0
======
Release Summary
---------------
Adding new SPN module
New Modules
-----------
- spn - Configures SPNs for SQL Server.
v0.5.0
======
Release Summary
---------------
CI and testing improvements, along with the final availability group module ag_replica.
Minor Changes
-------------
- Remove CI support for Ansible 2.10
New Modules
-----------
- ag_listener - Configures an availability group listener.
- ag_replica - Configures an availability group replica.
v0.4.0
======
Release Summary
---------------
Two new AlwaysOn modules and a few consistency fixes!
Minor Changes
-------------
- Test for 'Name' property for sa module after dbatools release 1.1.95 standardizes command outputs. (https://github.com/dataplat/dbatools/releases/tag/v1.1.95)
Breaking Changes / Porting Guide
--------------------------------
- All modules should use a bool 'enabled' instead of a string 'status' to control object state.
New Modules
-----------
- availability_group - Configures availability group(s).
- hadr - Enable or disable HADR.
v0.3.0
======
Release Summary
---------------
New sa module and fixes for login related modules.
Minor Changes
-------------
- Fix logic to properly pass password policy options to function in the login module.
New Modules
-----------
- sa - Configure the 'sa' login for security best practices.
v0.2.0
======
Release Summary
---------------
Code cleanup, testing improvements, new _info module!
Minor Changes
-------------
- Add DbaTools module requirement to documentation and fix missing examples. (https://github.com/lowlydba/lowlydba.sqlserver/pull/47)
- Utilize PowerShell Requires for dbatools min version needs instead of custom function. Consolidate/standardize credential setup and serialization. (https://github.com/lowlydba/lowlydba.sqlserver/pull/48)
New Modules
-----------
- instance_info - Returns basic information for a SQL Server instance.
v0.1.1
======
Release Summary
---------------
Add database tag for Galaxy
v0.1.0
======
Release Summary
---------------
It's a release! First version to publish to Ansible Galaxy.
New Modules
-----------
- agent_job - Configures a SQL Agent job.
- agent_job_category - Configures a SQL Agent job category.
- agent_job_schedule - Configures a SQL Agent job schedule.
- agent_job_step - Configures a SQL Agent job step.
- database - Creates and configures a database.
- login - Configures a login for the target SQL Server instance.
- maintenance_solution - Install/update Maintenance Solution
- memory - Sets the maximum memory for a SQL Server instance.
- nonquery - Executes a generic nonquery.
- resource_governor - Configures the resource governor on a SQL Server instance.
- rg_resource_pool - Configures a resource pool for use by the Resource Governor.
- rg_workload_group - Configures a workload group for use by the Resource Governor.
- sp_configure - Make instance level system configuration changes via sp_configure.
- sp_whoisactive - Install/update sp_whoisactive by Adam Mechanic.
- traceflag - Enable or disable global trace flags on a SQL Server instance.

View File

@@ -0,0 +1,3 @@
# Community Code of Conduct
Please see the official [Ansible Community Code of Conduct](https://docs.ansible.com/ansible/latest/community/code_of_conduct.html).

View File

@@ -0,0 +1,3 @@
# Contributing
Refer to the [Contributing guidelines](https://github.com/ansible/community-docs/blob/main/contributing.rst).

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,2 @@
lowlydba
briantist

View File

@@ -0,0 +1,32 @@
{
"collection_info": {
"namespace": "lowlydba",
"name": "sqlserver",
"version": "1.3.1",
"authors": [
"John McCall (github.com/lowlydba)"
],
"readme": "README.md",
"tags": [
"sqlserver",
"mssql",
"database"
],
"description": "Ansible collection using PowerShell to configure and maintain SQL Server.",
"license": [],
"license_file": "LICENSE",
"dependencies": {},
"repository": "https://github.com/LowlyDBA/lowlydba.sqlserver",
"documentation": "https://lowlydba.github.io/lowlydba.sqlserver",
"homepage": "https://github.com/LowlyDBA/lowlydba.sqlserver",
"issues": "https://github.com/LowlyDBA/lowlydba.sqlserver/issues"
},
"file_manifest_file": {
"name": "FILES.json",
"ftype": "file",
"chksum_type": "sha256",
"chksum_sha256": "84cd6ed3f803e766ba81e7a8b79a2347820c2c28333e7720260378cfcb58831d",
"format": 1
},
"format": 1
}

View File

@@ -0,0 +1,139 @@
# lowlydba.sqlserver Collection for Ansible
![GPL v3](https://img.shields.io/github/license/lowlydba/lowlydba.sqlserver)
[![CI](https://github.com/lowlydba/lowlydba.sqlserver/actions/workflows/ansible-test.yml/badge.svg)](https://github.com/lowlydba/lowlydba.sqlserver/actions/workflows/ansible-test.yml)
[![CI (Windows)](https://github.com/lowlydba/lowlydba.sqlserver/actions/workflows/ansible-test-windows.yml/badge.svg)](https://github.com/lowlydba/lowlydba.sqlserver/actions/workflows/ansible-test-windows.yml)
[![codecov](https://codecov.io/gh/lowlydba/lowlydba.sqlserver/branch/main/graph/badge.svg?token=3TW3VBCn9N)](https://codecov.io/gh/lowlydba/lowlydba.sqlserver)
- [Modules](#modules)
- [Code of Conduct](#code-of-conduct)
- [Communication](#communication)
- [Contributing to this collection](#contributing-to-this-collection)
- [Collection maintenance](#collection-maintenance)
- [Tested with](#tested-with)
- [External requirements](#external-requirements)
- [Using this collection](#using-this-collection)
- [Installing the Collection from Ansible Galaxy](#installing-the-collection-from-ansible-galaxy)
- [Release notes](#release-notes)
- [Releasing](#releasing)
## Modules
For the most up to date information, see the [plugin section](https://lowlydba.github.io/lowlydba.sqlserver/branch/main/collections/lowlydba/sqlserver/index.html#plugins-in-lowlydba-sqlserver) of the documentation for this collection (<https://lowlydba.github.io/lowlydba.sqlserver>).
For the current version contained in the Ansible Community General Collection, see the [official documentation](https://docs.ansible.com/ansible/latest/collections/lowlydba/sqlserver/index.html).
## Code of Conduct
We follow the [Ansible Code of Conduct](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html) in all our interactions within this project.
If you encounter abusive behavior, please refer to the [policy violations](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html#policy-violations) section of the Code for information on how to raise a complaint.
## Communication
Join us in the `#ansible` (general use questions and support), `#ansible-community` (community and collection development questions), and other [IRC channels](https://docs.ansible.com/ansible/devel/community/communication.html#irc-channels).
We take part in the global quarterly [Ansible Contributor Summit](https://github.com/ansible/community/wiki/Contributor-Summit) virtually or in-person. Track [The Bullhorn newsletter](https://eepurl.com/gZmiEP) and join us.
For more information about communication, refer to the [Ansible Communication guide](https://docs.ansible.com/ansible/devel/community/communication.html).
## Contributing to this collection
The content of this collection is made by people like you, a community of individuals collaborating on making the world better through developing automation software. We are actively accepting new contributors.
We use the following guidelines:
- [CONTRIBUTING.md](CONTRIBUTING.md)
- [REVIEW_CHECKLIST.md](REVIEW_CHECKLIST.md)
- [Ansible Community Guide](https://docs.ansible.com/ansible/latest/community/index.html)
- [Ansible Development Guide](https://docs.ansible.com/ansible/devel/dev_guide/index.html)
- [Ansible Collection Development Guide](https://docs.ansible.com/ansible/devel/dev_guide/developing_collections.html#contributing-to-collections)
## Collection maintenance
The current maintainers are listed in the [MAINTAINERS](MAINTAINERS) file. If you have questions or need help, feel free to mention them in the proposals.
To learn how to maintain / become a maintainer of this collection, refer to the [Maintainer guidelines](MAINTAINING.md).
## Tested with
### Ansible
- 2.11
- 2.12
- 2.13
- 2.14
- dlevel
### SQL Server
- SQL Server 2000 - current (via DBATools)
- Azure SQL Database Managed Instance - YMMV
## External requirements
- PowerShell modules
- [dbatools][dbatools] >= 1.1.112
- [dbops][dbops] >= 0.8.0
## Using this collection
### Installing the Collection from Ansible Galaxy
Before using this collection, you need to install it with the Ansible Galaxy command-line tool:
```bash
ansible-galaxy collection install lowlydba.sqlserver
```
You can also include it in a `requirements.yml` file and install it with `ansible-galaxy collection install -r requirements.yml`, using the format:
```yaml
---
collections:
- name: lowlydba.sqlserver
```
Note that if you install the collection from Ansible Galaxy, it will not be upgraded automatically when you upgrade the `ansible` package. To upgrade the collection to the latest available version, run the following command:
```bash
ansible-galaxy collection install lowlydba.sqlserver --upgrade
```
You can also install a specific version of the collection, for example, if you need to downgrade when something is broken in the latest version (please report an issue in this repository). Use the following syntax to install version `0.1.0`:
```bash
ansible-galaxy collection install lowlydba.sqlserver:==0.1.0
```
See [Ansible Using collections](https://docs.ansible.com/ansible/devel/user_guide/collections_using.html) for more details.
## Releasing
### Release notes
See the [changelog](https://github.com/lowlydba/lowlydba.sqlserver/tree/main/CHANGELOG.rst).
### Next Release
No major release planned currently.
### Schedule
- Minor releases and patches will aim to be released within 2 weeks of being merged into `main` or when necessary.
- Non-current minor versions will not generally be patched, since there is little expected breaking of backwards compatibility.
- If this does occur, an exception can be made.
### Versioning
This project adheres to [semantic versioning](https://semver.org/) as tracked in [`galaxy.yml`](https://github.com/lowlydba/lowlydba.sqlserver/blob/main/galaxy.yml).
### Deprecation
- Deprecations are done by version number (not by date).
- New deprecations can be added during every minor release, under the condition that they do not break backwards compatibility.
- Deprecations are expected to have a deprecation cycle of at least 2 major versions (i.e. ~1 year). Maintainers can use a longer deprecation cycle if they want to support the old code for that long.
<!-- Link shortcuts -->
[dbatools]: https://dbatools.io
[dbops]: https://github.com/dataplat/dbops

View File

@@ -0,0 +1,407 @@
ancestor: null
releases:
0.1.0:
changes:
release_summary: It's a release! First version to publish to Ansible Galaxy.
fragments:
- v0.1.0_summary.yml
modules:
- description: Configures a SQL Agent job.
name: agent_job
namespace: ''
- description: Configures a SQL Agent job category.
name: agent_job_category
namespace: ''
- description: Configures a SQL Agent job schedule.
name: agent_job_schedule
namespace: ''
- description: Configures a SQL Agent job step.
name: agent_job_step
namespace: ''
- description: Creates and configures a database.
name: database
namespace: ''
- description: Configures a login for the target SQL Server instance.
name: login
namespace: ''
- description: Install/update Maintenance Solution
name: maintenance_solution
namespace: ''
- description: Sets the maximum memory for a SQL Server instance.
name: memory
namespace: ''
- description: Executes a generic nonquery.
name: nonquery
namespace: ''
- description: Configures the resource governor on a SQL Server instance.
name: resource_governor
namespace: ''
- description: Configures a resource pool for use by the Resource Governor.
name: rg_resource_pool
namespace: ''
- description: Configures a workload group for use by the Resource Governor.
name: rg_workload_group
namespace: ''
- description: Make instance level system configuration changes via sp_configure.
name: sp_configure
namespace: ''
- description: Install/update sp_whoisactive by Adam Mechanic.
name: sp_whoisactive
namespace: ''
- description: Enable or disable global trace flags on a SQL Server instance.
name: traceflag
namespace: ''
release_date: '2022-03-30'
0.1.1:
changes:
release_summary: Add database tag for Galaxy
fragments:
- v0.1.1_summary.yml
release_date: '2022-03-31'
0.10.0:
changes:
minor_changes:
- Update minimum required DBATools version universally to 1.1.108 to accommodate
new tcp module.
release_summary: The first_responder_kit and tcp_port modules, along with a
bump in the required dbatools version.
fragments:
- 105-update-dbatools-version.yml
- v0-10-0-release-summary.yml
modules:
- description: Install/update the First Responder Kit scripts.
name: first_responder_kit
namespace: ''
- description: Sets the TCP port for the instance.
name: tcp_port
namespace: ''
release_date: '2022-06-27'
0.10.1:
changes:
bugfixes:
- Fix change detection in resource_governor module.
release_summary: Bug fix for resource_governor.
fragments:
- 108-rg-bug-fix.yml
- v0-10-1-release-summary.yml
release_date: '2022-06-28'
0.11.0:
changes:
release_summary: Adding new dbops module.
fragments:
- 0-11-0-release-summary.yml
modules:
- description: Runs migration scripts against a database.
name: install_script
namespace: ''
release_date: '2022-07-03'
0.11.1:
changes:
bugfixes:
- Fix `availability_group` module so that NUL backups can be properly taken
if needed.
- Fix incorrect examples in `availability_group` module documentation.
- Fix incorrect examples in `install_script` module documentation.
- Fix incorrect examples in `spn` module documentationb.
- Fixed bugs where adding replica did not work properly for several reasons.
release_summary: Bug fixes for AlwaysOn related modules and fixing errors in
some documentation examples.
fragments:
- 0-11-1-release-summary.yml
- 113-fix-ag-module.yml
- x-fix-spn-docs.yml
release_date: '2022-07-06'
0.11.2:
changes:
release_summary: Bumping required dbatools version to ensure the `restore` module
works on MacOS PowerShell Core (https://github.com/dataplat/dbatools/pull/8435).
fragments:
- 0-11-2-release-summary.yml
release_date: '2022-07-09'
0.2.0:
changes:
minor_changes:
- Add DbaTools module requirement to documentation and fix missing examples.
(https://github.com/lowlydba/lowlydba.sqlserver/pull/47)
- Utilize PowerShell Requires for dbatools min version needs instead of custom
function. Consolidate/standardize credential setup and serialization. (https://github.com/lowlydba/lowlydba.sqlserver/pull/48)
release_summary: Code cleanup, testing improvements, new _info module!
fragments:
- 47-improve-module-documentation.yml
- 48-cleanup-utils.yml
modules:
- description: Returns basic information for a SQL Server instance.
name: instance_info
namespace: ''
release_date: '2022-04-04'
0.3.0:
changes:
minor_changes:
- Fix logic to properly pass password policy options to function in the login
module.
release_summary: New sa module and fixes for login related modules.
fragments:
- 55-fix-login-param.yml
- v0.3.0-release-summary.yml
modules:
- description: Configure the 'sa' login for security best practices.
name: sa
namespace: ''
release_date: '2022-04-05'
0.4.0:
changes:
breaking_changes:
- All modules should use a bool 'enabled' instead of a string 'status' to control
object state.
minor_changes:
- Test for 'Name' property for sa module after dbatools release 1.1.95 standardizes
command outputs. (https://github.com/dataplat/dbatools/releases/tag/v1.1.95)
release_summary: Two new AlwaysOn modules and a few consistency fixes!
fragments:
- 0.4.0-release-summary.yml
- 56-test-for-login-name.yml
- 60-standardize-enabled-option.yml
modules:
- description: Configures availability group(s).
name: availability_group
namespace: ''
- description: Enable or disable HADR.
name: hadr
namespace: ''
release_date: '2022-04-27'
0.5.0:
changes:
minor_changes:
- Remove CI support for Ansible 2.10
release_summary: CI and testing improvements, along with the final availability
group module ag_replica.
fragments:
- 70-deprecate-ansible-2.10.yml
- release-summary.yml
modules:
- description: Configures an availability group listener.
name: ag_listener
namespace: ''
- description: Configures an availability group replica.
name: ag_replica
namespace: ''
release_date: '2022-05-11'
0.6.0:
changes:
release_summary: Adding new SPN module
fragments:
- release-summary-0-6-0.yml
modules:
- description: Configures SPNs for SQL Server.
name: spn
namespace: ''
release_date: '2022-05-20'
0.7.0:
changes:
release_summary: Add module for DBA Multitool.
fragments:
- release-summary-0-7-0.yml
modules:
- description: Install/update the DBA Multitool suite by John McCAll
name: dba_multitool
namespace: ''
release_date: '2022-05-21'
0.8.0:
changes:
bugfixes:
- Fix inability to enable an agent job schedule after it has been disabled.
minor_changes:
- Standardize use of 'database' vs 'database_name' in all documentation and
options specs. Not a breaking change.
release_summary: A few small fixes and the new 'backup' module.
fragments:
- 83-fix-agent-schedule.yml
- 84-standardize-database-option.yml
modules:
- description: Performs a backup operation.
name: backup
namespace: ''
release_date: '2022-05-31'
0.9.0:
changes:
bugfixes:
- backup - Only use blocksize when specified.
fragments:
- 90-fix-backup-blocksize.yml
modules:
- description: Performs a restore operation.
name: restore
namespace: ''
release_date: '2022-06-18'
0.9.1:
changes:
bugfixes:
- Allow agent job steps to be removed by specifying the step ID only. This is
likely needed in cleanup of steps from previous job configurations.
release_summary: Bugfix!
fragments:
- 0-9-1-release_sumary.yml
- 95-fix-agent-job-step-removal.yml
release_date: '2022-06-21'
0.9.2:
changes:
bugfixes:
- agent_job - Fix incorrectly reported change status when no change occurred.
- agent_job_schedule - Fix incorrectly reported change status when no change
occurred.
- agent_job_step - Fix incorrectly reported change status when no change occurred.
release_summary: Bugfixes for agent related modules that incorrectly reported
change statuses.
fragments:
- 97-fix-agent-related-status.yml
- 97-release-summary.yml
release_date: '2022-06-22'
0.9.3:
changes:
bugfixes:
- memory - Fix improper changed detection.
release_summary: More change detection fixing.
fragments:
- 100-fix-memory.yml
- v0-9-3-release-summary.yml
release_date: '2022-06-22'
1.0.0:
changes:
release_summary: "Bumping to version 1.0.0 now that this collection is being
used in production in at least one place \U0001F389"
fragments:
- v1-release-summary.yml
release_date: '2022-08-03'
1.0.1:
changes:
bugfixes:
- Fixed bug in how the classifier function name is being assigned to the variable
in the resource_governor module.
release_summary: Minor bug fix.
fragments:
- 1-0-1-release_summary.yml
- resource_governor.yml
release_date: '2022-08-20'
1.0.2:
changes:
bugfixes:
- _SqlServerUtils module_util - added explicit license to private module util
(https://github.com/lowlydba/lowlydba.sqlserver/pull/119).
- meta/runtime.yml - updated out of date runtime version info (https://github.com/lowlydba/lowlydba.sqlserver/pull/119).
- most modules - fixed alignment, formatting, and typos in module documentation
(https://github.com/lowlydba/lowlydba.sqlserver/pull/119).
release_summary: Minor documentation bugfixes and enhancements as requested
in the Ansible inclusion process.
fragments:
- 119-doc-updates.yml
- v1-0-2-release-summary.yml
release_date: '2022-08-29'
1.0.3:
changes:
bugfixes:
- Minor documentation fixes (https://github.com/lowlydba/lowlydba.sqlserver/pull/122).
release_summary: Minor documentation fixes from the second Ansible inclusion
review.
fragments:
- 122-doc-fixes.yml
- v1-0-3-release-summary.yml
release_date: '2022-09-03'
1.0.4:
changes:
bugfixes:
- Fix cleanup_time default to match documentation default & lint fixes (https://github.com/lowlydba/lowlydba.sqlserver/pull/127).
release_summary: Minor fixes to resolve new dlevel sanity checks.
fragments:
- 127-fix-doc-check.yml
- release-summary.yml
release_date: '2022-11-05'
1.1.0:
changes:
release_summary: Adding a new user module.
modules:
- description: Configures a user within a database
name: user
namespace: ''
release_date: '2022-11-12'
1.1.1:
changes:
minor_changes:
- modules - all modules now document their platform and support for check mode
in their attributes documentation (https://github.com/lowlydba/lowlydba.sqlserver/pull/134).
fragments:
- 137-add-attributes.yml
release_date: '2022-11-28'
1.1.2:
changes:
bugfixes:
- Removed the default value for xp_dirtree to allow compatibility with Azure
SQL Mangaed instances (https://github.com/lowlydba/lowlydba.sqlserver/pull/141)
release_summary: Bug fix for Azure Database Managed Instance compatibility.
fragments:
- 1-1-2-release-summary.yml
- xpdirtree_sql_mi_bugfix.yml
release_date: '2022-12-02'
1.1.3:
changes:
bugfixes:
- Removed default value for reuse_source_folder_structure to fix compatability
with SQL MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/145)
release_summary: Another minor fix to increase SQL Managed Instance support.
fragments:
- reuse_source_folder_structure_sql_mi_bugfix.yml
- v1-1-3-release-summary.yml
release_date: '2022-12-05'
1.2.0:
changes:
bugfixes:
- Removed default value for ReplaceDbNameInFile to fix compatability with SQL
MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/148)
minor_changes:
- Fixed typo in the traceflag module's documentation. (https://github.com/lowlydba/lowlydba.sqlserver/pull/150)
- Return "RestartRequired" when a module performs changes that require an addition
service restart to take effect. (https://github.com/lowlydba/lowlydba.sqlserver/pull/150/)
release_summary: Azure SQL MI compatibility fixes & indicating required restarts
for settings changes.
fragments:
- 1-2-0-release-summary.yml
- 150-restart-indicator.yml
- ReplaceDbNameInFile_sql_mi_bugfix.yml
release_date: '2022-12-05'
1.2.1:
changes:
bugfixes:
- Added missing mapping for UseDestinationDefaultDirectories (https://github.com/lowlydba/lowlydba.sqlserver/pull/153)
- Removed default value for KeepCDC to fix compatability with SQL MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/153)
- Removed default value for UseDestinationDefaultDirectories to fix compatability
with SQL MI (https://github.com/lowlydba/lowlydba.sqlserver/pull/153)
release_summary: More Azure SQL Managed Instance compatibility fixes.
fragments:
- 1-2-1-release_summary.yml
- 153-additional_sql_mi_fixes.yml
release_date: '2022-12-06'
1.3.0:
changes:
minor_changes:
- Adding a new credential module
release_summary: New module to manage credentials added!
fragments:
- 1-3-0-release_summary.yml
- add_credential_module.yml
modules:
- description: Configures a credential on a SQL server
name: credential
namespace: ''
release_date: '2022-12-09'
1.3.1:
changes:
bugfixes:
- Fixes to incorrect variable reference in Login module (https://github.com/lowlydba/lowlydba.sqlserver/pull/161)
minor_changes:
- Update login module documentation to indicate result will always be changed
when a password is supplied. (https://github.com/lowlydba/lowlydba.sqlserver/pull/167)
release_summary: Small bugfixes and documentation enhancements.
fragments:
- 1-3-1-release_summary.yml
- 167-update-login-docs.yml
- fix_sa.yml
release_date: '2022-12-18'

View File

@@ -0,0 +1,30 @@
# https://github.com/ansible-community/antsibull-changelog/blob/main/docs/changelogs.rst
changelog_filename_template: ../CHANGELOG.rst
changelog_filename_version_depth: 0
changes_file: changelog.yaml
changes_format: combined
keep_fragments: false
mention_ancestor: true
new_plugins_after_name: removed_features
notesdir: fragments
prelude_section_name: release_summary
prelude_section_title: Release Summary
sections:
- - major_changes
- Major Changes
- - minor_changes
- Minor Changes
- - breaking_changes
- Breaking Changes / Porting Guide
- - deprecated_features
- Deprecated Features
- - removed_features
- Removed Features (previously deprecated)
- - security_fixes
- Security Fixes
- - bugfixes
- Bugfixes
- - known_issues
- Known Issues
title: lowlydba.sqlserver
trivial_section_name: trivial

View File

@@ -0,0 +1,2 @@
---
requires_ansible: ">=2.11"

View File

@@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
class ModuleDocFragment(object):
DOCUMENTATION = r'''
options: {}
'''
CHECK_MODE = r'''
options: {}
attributes:
check_mode:
support: full
description: Can run in check_mode and return changed status prediction without modifying target.
'''
CHECK_MODE_READ_ONLY = r'''
options: {}
attributes:
check_mode:
support: full
description: This module is "read only" and operates the same regardless of check mode.
'''
PLATFORM_ALL = r'''
options: {}
attributes:
platform:
platforms: all
support: full
description: Target OS/families that can be operated against.
'''
PLATFORM_WIN = r'''
options: {}
attributes:
platform:
platforms: Windows
support: full
description: Target OS/families that can be operated against.
'''

View File

@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Options for authenticating with SQL Authentication.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
class ModuleDocFragment(object):
DOCUMENTATION = r'''
options:
sql_instance:
description:
- The SQL Server instance to modify.
type: str
required: true
sql_username:
description:
- Username for SQL Authentication.
type: str
required: false
sql_password:
description:
- Password for SQL Authentication.
type: str
required: false
'''

View File

@@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Options for object state.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
class ModuleDocFragment(object):
DOCUMENTATION = r'''
options:
state:
description:
- Whether or not the object should be C(present) or C(absent).
required: false
type: str
default: 'present'
choices: ['present', 'absent']
'''

View File

@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Private
function Get-LowlyDbaSqlServerAuthSpec {
<#
.SYNOPSIS
Output the auth spec used by every module.
.DESCRIPTION
Standardized way to access the common auth spec for modules.
Uses the recommended Ansible naming convention.
#>
@{
options = @{
sql_instance = @{type = 'str'; required = $true }
sql_username = @{type = 'str'; required = $false }
sql_password = @{type = 'str'; required = $false; no_log = $true }
}
required_together = @(
, @('sql_username', 'sql_password')
)
}
}
function Get-SqlCredential {
<#
.SYNOPSIS
Build a credential object for SQL Authentication.
.DESCRIPTION
Standardized way to build a SQL Credential object that is required for SQL Authentication.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateScript({ $_.GetType().FullName -eq 'Ansible.Basic.AnsibleModule' })]
$Module
)
try {
$sqlInstance = $module.Params.sql_instance
if ($null -ne $Module.Params.sql_username) {
[securestring]$secPassword = ConvertTo-SecureString $Module.Params.sql_password -AsPlainText -Force
[pscredential]$sqlCredential = New-Object System.Management.Automation.PSCredential ($Module.Params.sql_username, $secPassword)
}
else {
$sqlCredential = $null
}
return $sqlInstance, $sqlCredential
}
catch {
Write-Error ("Error building Credential for SQL Authentication spec.")
}
}
function ConvertTo-SerializableObject {
<#
.SYNOPSIS
Transforms some members of a DbaTools result objects to be more serialization-friendly and prevent infinite recursion.
.DESCRIPTION
Stringifies version properties so we don't get serialized [System.Version] objects which aren't very useful.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Object]
$InputObject,
[Parameter()]
[string[]]
$ExcludeProperty = @(
<#
Returning a list of properties as a property is redundant.
#>
'Properties',
<#
Urn is not useful.
#>
'Urn',
<#
ExecutionManager can contain a login password in plain text.
#>
'ExecutionManager',
<#
UserData is not useful.
#>
'UserData',
<#
ParentCollection is redundant.
#>
'ParentCollection',
<#
DatabaseEngineEdition is not useful.
#>
'DatabaseEngineEdition',
<#
DatabaseEngineType is not useful.
#>
'DatabaseEngineType',
<#
ServerVersion is not useful.
#>
'ServerVersion',
<#
Server is redundant.
#>
'Server',
<#
Parent is not useful.
#>
'Parent'
),
[bool]$UseDefaultProperty = $true
)
Begin {
# We need to remove this type data so that arrays don't get serialized weirdly.
# In some cases, an array gets serialized as an object with a Count and Value property where the value is the actual array.
# See: https://stackoverflow.com/a/48858780/3905079
# This only affects Windows PowerShell.
# This has to come after the AnsibleModule is created, otherwise it will break the sanity tests.
if (-not $IsLinux) {
Remove-TypeData -TypeName System.Array -ErrorAction SilentlyContinue
}
}
Process {
$defaultProperty = $InputObject.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames
if ($defaultProperty -and $UseDefaultProperty) {
$objectProperty = $InputObject.PSObject.Properties | Where-Object { $_.Name -in $defaultProperty -and $_.Name -notin $ExcludeProperty }
}
else {
$objectProperty = $InputObject.PSObject.Properties | Where-Object { $_.Name -notin $ExcludeProperty }
}
$properties = foreach ($p in $objectProperty) {
$pName = $p.Name
$pValue = $p.Value
switch ($p) {
{ $null -eq $pValue } {
@{
Name = $pName
Expression = { $null }.GetNewClosure()
}
break
}
{ $pValue -is [datetime] } {
@{
Name = $pName
Expression = { $pValue.ToString('o') }.GetNewClosure()
}
break
}
{ $pValue -is [enum] -or $pValue -is [type] } {
@{
Name = $pName
Expression = { $pValue.ToString() }.GetNewClosure()
}
break
}
{ $pValue.GetType().Name -like '*Collection' } {
@{
Name = $pName
Expression = { [string[]]($pValue.Name) }.GetNewClosure()
}
break
}
{ $pValue.GetType().Name -eq 'User' } {
@{
Name = $pName
Expression = { [string[]]($pValue.Name) }.GetNewClosure()
}
break
}
default { $pName }
}
}
return $InputObject | Select-Object -Property $properties
}
}
$exportMembers = @("Get-SqlCredential", "ConvertTo-SerializableObject", "Get-LowlyDbaSqlServerAuthSpec")
Export-ModuleMember -Function $exportMembers

View File

@@ -0,0 +1,86 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
ag_name = @{type = 'str'; required = $true }
listener_name = @{type = 'str'; required = $true }
ip_address = @{type = 'str'; required = $false }
subnet_ip = @{type = 'str'; required = $false }
subnet_mask = @{type = 'str'; required = $false; default = '255.255.255.0' }
port = @{type = 'int'; required = $false; default = 1433 }
dhcp = @{type = 'bool'; required = $false; default = $false }
state = @{type = "str"; required = $false; default = "present"; choices = @("present", "absent") }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$agName = $module.Params.ag_name
$listenerName = $module.Params.listener_name
$subnetIp = $module.Params.subnet_ip
$subnetMask = $module.Params.subnet_mask
$ipAddress = $module.Params.ip_address
$port = $module.Params.port
$dhcp = $module.Params.dhcp
$state = $module.Params.state
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{
"*:SqlInstance" = $sqlInstance
"*:SqlCredential" = $sqlCredential
"*:EnableException" = $true
"*:Confirm" = $false
"*:WhatIf" = $checkMode
}
try {
$existingListener = Get-DbaAgListener -AvailabilityGroup $agName -Listener $listenerName
if ($state -eq "present") {
if ($null -eq $existingListener) {
$listenerParams = @{
AvailabilityGroup = $agName
Name = $listenerName
Port = $port
Dhcp = $dhcp
SubnetMask = $subnetMask
}
if ($null -ne $ipAddress) {
$listenerParams.Add("IPAddress", $ipAddress)
}
if ($null -ne $subnetIp) {
$listenerParams.Add("SubnetIP", $subnetIp)
}
$output = Add-DbaAgListener @listenerParams
$module.Result.changed = $true
}
elseif ($existingListener.Port -ne $port) {
$output = Set-DbaAgListener -AvailabilityGroup $agName -Listener $listenerName -Port $port
$module.Result.changed = $true
}
}
elseif ($state -eq "absent") {
if ($null -ne $existingListener) {
$output = Remove-DbaAgListener -AvailabilityGroup $agName -Listener $listenerName
$module.Result.changed = $true
}
}
if ($output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Configuring availability group listener failed: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,84 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: ag_listener
short_description: Configures an availability group listener
description:
- Creates an Availability Group Listener for an existing availability group.
version_added: 0.5.0
options:
ag_name:
description:
- Name of the target availability group.
type: str
required: true
listener_name:
description:
- Name of the Listener to be configured.
type: str
required: true
ip_address:
description:
- IP address(es) of the listener. Comma separated if multiple.
type: str
required: false
subnet_ip:
description:
- Subnet IP address(es) of the listener. Comma separated if multiple.
type: str
required: false
subnet_mask:
description:
- Sets the subnet IP mask(s) of the availability group listener. Comma separated if multiple.
type: str
required: false
default: 255.255.255.0
port:
description:
- Sets the port number used to communicate with the availability group.
type: int
required: false
default: 1433
dhcp:
description:
- Indicates whether the listener uses DHCP.
type: bool
required: false
default: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create Availability Group
lowlydba.sqlserver.availability_group:
sql_instance: sql-01.myco.io
ag_name: AG_MyDatabase
- name: Create AG Listener
lowlydba.sqlserver.ag_listener:
sql_instance_primary: sql-01.myco.io
ag_name: AG_MyDatabase
listener_name: aglMyDatabase
ip_address: 10.0.20.20,10.1.77.77
subnet_ip: 255.255.252.0
subnet_mask: 255.255.255.0
'''
RETURN = r'''
data:
description: Output from the C(Add-DbaAgListener) or C(Set-DbaAgListener) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,193 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
sql_instance_replica = @{type = 'str'; required = $true }
sql_username_replica = @{type = 'str'; required = $false }
sql_password_replica = @{type = 'str'; required = $false; no_log = $true }
ag_name = @{type = 'str'; required = $true }
endpoint = @{type = 'str'; required = $false; default = 'hadr_endpoint' }
endpoint_url = @{type = 'str'; required = $false }
backup_priority = @{type = 'int'; required = $false; default = 50 }
failover_mode = @{
type = 'str'
required = $false
default = 'Manual'
choices = @('Manual', 'Automatic')
}
availability_mode = @{
type = 'str'
required = $false; default = 'AsynchronousCommit'
choices = @('SynchronousCommit', 'AsynchronousCommit')
}
seeding_mode = @{
type = 'str'
required = $false
default = 'Automatic'
choices = @('Manual', 'Automatic')
}
connection_mode_in_primary_role = @{
type = 'str'
required = $false
default = 'AllowAllConnections'
choices = @('AllowReadIntentConnectionsOnly', 'AllowAllConnections')
}
connection_mode_in_secondary_role = @{
type = 'str'
required = $false
default = 'AllowNoConnections'
choices = @('AllowNoConnections', 'AllowReadIntentConnectionsOnly', 'AllowAllConnections')
}
read_only_routing_connection_url = @{
type = 'str'
required = $false
}
read_only_routing_list = @{
type = 'str'
required = $false
}
cluster_type = @{
type = 'str'
required = $false
default = 'Wsfc'
choices = @('Wsfc', 'External', 'None')
}
configure_xe_session = @{ type = 'bool'; required = $false; default = $false }
session_timeout = @{ type = 'int'; required = $false }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
required_together = @(
, @('sql_username_replica', 'sql_password_replica')
)
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$readOnlyRoutingConnectionUrl = $module.params.read_only_routing_connection_url
$readOnlyRoutingList = $module.Params.read_only_routing_list
$failoverMode = $module.Params.failover_mode
$seedingMode = $module.Params.seeding_mode
$agName = $module.Params.ag_name
$clusterType = $module.Params.cluster_type
$availabilityMode = $module.Params.availability_mode
$replicaSqlInstance = $module.Params.sql_instance_replica
$connectionModeInPrimaryRole = $module.Params.connection_mode_in_primary_role
$connectionModeInSecondaryRole = $module.Params.connection_mode_in_secondary_role
$configureXESession = $module.Params.configure_xe_session
$state = $module.Params.state
[nullable[int]]$sessionTimeout = $module.Params.session_timeout
$endpoint = $module.Params.endpoint
$endpointUrl = $module.Params.endpoint_url
$backupPriority = $module.Params.backup_priority
if ($null -ne $module.Params.sql_username_replica) {
[securestring]$replicaSecPassword = ConvertTo-SecureString $Module.Params.sql_password_replica -AsPlainText -Force
[pscredential]$replicaSqlCredential = New-Object System.Management.Automation.PSCredential ($Module.Params.sql_username_replica, $replicaSecPassword)
}
if ($null -eq $replicaSqlCredential) {
$replicaSqlCredential = $sqlCredential
}
$module.Result.changed = $false
$checkMode = $module.CheckMode
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
try {
$replicaInstance = Connect-DbaInstance -SqlInstance $replicaSqlInstance -SqlCredential $replicaSqlCredential
$allReplicas = Get-DbaAgReplica -SqlInstance $replicaSqlInstance -SqlCredential $replicaSqlCredential -AvailabilityGroup $agName
$existingReplica = $allReplicas | Where-Object Name -eq $replicaInstance.DomainInstanceName
if ($state -eq "present") {
$addReplicaSplat = @{
SqlInstance = $replicaSqlInstance
SqlCredential = $replicaSqlCredential
Endpoint = $endpoint
AvailabilityMode = $availabilityMode
FailoverMode = $failoverMode
BackupPriority = $backupPriority
ConnectionModeInPrimaryRole = $connectionModeInPrimaryRole
ConnectionModeInSecondaryRole = $connectionModeInSecondaryRole
SeedingMode = $seedingMode
ClusterType = $clusterType
}
if ($null -ne $readOnlyRoutingList) {
$addReplicaSplat.Add("ReadOnlyRoutingList", $readOnlyRoutingList)
}
if ($null -ne $readOnlyRoutingConnectionUrl) {
$addReplicaSplat.Add("ReadOnlyRoutingConnectionUrl", $readOnlyRoutingConnectionUrl)
}
if ($null -ne $endpointUrl) {
$addReplicaSplat.Add("EndpointUrl", $endpointUrl)
}
if ($configureXESession -eq $true) {
$addReplicaSplat.Add("ConfigureXESession", $true)
}
if ($null -ne $sessionTimeout) {
$addReplicaSplat.Add("SessionTimeout", $sessionTimeout)
}
if ($null -eq $existingReplica) {
$availabilityGroup = Get-DbaAvailabilityGroup -SqlInstance $sqlInstance -SqlCredential $sqlCredential -AvailabilityGroup $agName
$output = $availabilityGroup | Add-DbaAgReplica @addReplicaSplat
$module.Result.changed = $true
}
else {
$compareReplicaProperty = @(
'AvailabilityMode'
'FailoverMode'
'BackupPriority'
'ConnectionModeInPrimaryRole'
'ConnectionModeInSecondaryRole'
'SeedingMode'
'SessionTimeout'
'EndpointUrl'
)
$setReplicaSplat = @{}
$addReplicaSplat.GetEnumerator() | Where-Object Key -in $compareReplicaProperty | ForEach-Object { $setReplicaSplat.Add($_.Key, $_.Value) }
[string[]]$compareProperty = $setReplicaSplat.Keys
$replicaDiff = Compare-Object -ReferenceObject $setReplicaSplat -DifferenceObject $existingReplica -Property $compareProperty
$setReplicaSplat.Add("SqlInstance", $sqlInstance)
$setReplicaSplat.Add("SqlCredential", $sqlCredential)
$setReplicaSplat.Add("Replica", $existingReplica.Name)
$setReplicaSplat.Add("AvailabilityGroup", $agName)
if ($replicaDiff) {
$output = Set-DbaAgReplica @setReplicaSplat
$module.Result.changed = $true
}
}
}
}
catch {
$module.FailJson("Configuring Availability Group replica failed: $($_.Exception.Message)")
}
try {
if ($state -eq "absent") {
if ($null -ne $existingReplica) {
$output = $existingReplica | Remove-DbaAgReplica
$module.Result.changed = $true
}
}
}
catch {
$module.FailJson("Removing Availability Group replica failed: $($_.Exception.Message)")
}
try {
if ($output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error parsing results - operation likely completed: $($_.Exception.Message)")
}

View File

@@ -0,0 +1,147 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: ag_replica
short_description: Configures an availability group replica
description:
- Configures an availability group replica.
version_added: 0.5.0
options:
sql_instance_replica:
description:
- The SQL Server instance where of the replica to be configured.
type: str
required: true
sql_username_replica:
description:
- Username for SQL Authentication for the secondary replica.
type: str
required: false
sql_password_replica:
description:
- Password for SQL Authentication for the secondary replica.
type: str
required: false
ag_name:
description:
- Name of the Availability Group that will have the new replica joined to it.
type: str
required: true
endpoint:
description:
- By default, this command will attempt to find a DatabaseMirror endpoint. If one does not exist, it will create it.
type: str
required: false
default: 'hadr_endpoint'
endpoint_url:
description:
- By default, the property C(Fqdn) of C(Get-DbaEndpoint) is used as I(endpoint_url).
Use I(endpoint_url) if a different URL is required due to special network configurations.
type: str
required: false
backup_priority:
description:
- Sets the backup priority availability group replica.
type: int
default: 50
failover_mode:
description:
- Whether the replica have Automatic or Manual failover.
type: str
required: false
default: 'Manual'
choices: ['Automatic', 'Manual']
availability_mode:
description:
- Whether the replica should be Asynchronous or Synchronous.
type: str
required: false
default: 'AsynchronousCommit'
choices: ['AsynchronousCommit', 'SynchronousCommit']
seeding_mode:
description:
- Default seeding mode for the replica. Should remain as the default otherwise manual setup may be required.
type: str
required: false
default: 'Automatic'
choices: ['Automatic', 'Manual']
connection_mode_in_primary_role:
description:
- Which connections can be made to the database when it is in the primary role.
type: str
required: false
default: 'AllowAllConnections'
choices: ['AllowReadIntentConnectionsOnly','AllowAllConnections']
connection_mode_in_secondary_role:
description:
- Which connections can be made to the database when it is in the secondary role.
type: str
required: false
default: 'AllowNoConnections'
choices: ['AllowNoConnections','AllowReadIntentConnectionsOnly','AllowAllConnections']
read_only_routing_connection_url:
description:
- Sets the read only routing connection url for the availability replica.
type: str
required: false
read_only_routing_list:
description:
- Sets the read only routing ordered list of replica server names to use when redirecting read-only connections through this availability replica.
type: str
required: false
cluster_type:
description:
- Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.
type: str
required: false
default: 'Wsfc'
choices: ['Wsfc', 'External', 'None']
configure_xe_session:
description:
- Configure the AlwaysOn_health extended events session to start automatically as the SSMS wizard would do.
type: bool
default: false
session_timeout:
description:
- How many seconds an availability replica waits for a ping response from a connected replica before considering the connection to have failed.
type: int
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create Availability Group
lowlydba.sqlserver.availability_group:
sql_instance: sql-01.myco.io
ag_name: AG_MyDatabase
- name: Add a DR replica
lowlydba.sqlserver.ag_replica:
ag_name: 'AG_MyDatabase'
sql_instance_primary: sql-01.myco.io
sql_instance_replica: sql-02.myco.io
failover_mode: 'Manual'
availability_mode: 'Asynchronous'
seeding_mode: 'Automatic'
connection_mode_in_primary_role: 'AllowAllConnections'
connection_mode_in_secondary_role: 'AllowNoConnections'
'''
RETURN = r'''
data:
description: Output from the C(Add-DbaAgReplica) or C(Set-DbaAgReplica) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,133 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
job = @{type = 'str'; required = $true }
description = @{type = 'str'; required = $false; }
category = @{type = 'str'; required = $false; }
enabled = @{type = 'bool'; required = $false; default = $true }
owner_login = @{type = 'str'; required = $false; }
start_step_id = @{type = 'int'; required = $false; }
schedule = @{type = 'str'; required = $false; }
force = @{type = 'bool'; required = $false; default = $false }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$job = $module.Params.job
$description = $module.Params.description
$enabled = $module.Params.enabled
$ownerLogin = $module.Params.owner_login
$category = $module.Params.category
$schedule = $module.Params.schedule
[nullable[int]]$startStepId = $module.Params.start_step_id
$force = $module.Params.force
$state = $module.Params.state
$checkMode = $module.CheckMode
$module.Result.changed = $false
# Configure Agent job
try {
$existingJob = Get-DbaAgentJob -SqlInstance $sqlInstance -SqlCredential $sqlCredential -Job $job -EnableException
$output = $existingJob
if ($state -eq "absent") {
if ($null -ne $existingJob) {
$output = $existingJob | Remove-DbaAgentJob -Confirm:$false -WhatIf:$checkMode -EnableException
$module.Result.changed = $true
}
}
elseif ($state -eq "present") {
$jobParams = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Job = $job
WhatIf = $checkMode
Force = $force
EnableException = $true
}
if ($enabled -eq $false) {
$jobParams.add("Disabled", $true)
}
if ($null -ne $ownerLogin) {
$jobParams.add("OwnerLogin", $ownerLogin)
}
if ($null -ne $schedule) {
$jobParams.add("Schedule", $schedule)
}
if ($null -ne $category) {
$jobParams.add("Category", $category)
}
if ($null -ne $description) {
$jobParams.add("Description", $description)
}
if ($null -ne $startStepID) {
$jobParams.add("StartStepId", $startStepID)
}
# Create new job
if ($null -eq $existingJob) {
try {
$null = New-DbaAgentJob @jobParams
# Explicitly fetch the new job to make sure results don't suffer from SMO / Agent stale data bugs
$output = Get-DbaAgentJob -SqlInstance $sqlInstance -SqlCredential $sqlCredential -Job $job -EnableException
}
catch {
$module.FailJson("Failed creating new agent job: $($_.Exception.Message)", $_)
}
$module.Result.changed = $true
}
# Job exists
else {
# Need to serialize to prevent SMO auto refreshing
$old = ConvertTo-SerializableObject -InputObject $existingJob -UseDefaultProperty $false
if ($enabled -eq $true) {
$jobParams.Add("Enabled", $true)
}
$output = Set-DbaAgentJob @jobParams
if ($null -ne $output) {
$compareProperty = @(
"Category"
"Enabled"
"Name"
"OwnerLoginName"
"HasSchedule"
"Description"
"StartStepId"
)
$diff = Compare-Object -ReferenceObject $output -DifferenceObject $old -Property $compareProperty
if ($diff -or $checkMode) {
$module.Result.changed = $true
}
}
}
}
if ($output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error configuring SQL Agent job: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,84 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: agent_job
short_description: Configures a SQL Agent job
description:
- Configure a SQL Agent job, including which schedules and category it belongs to.
version_added: 0.1.0
options:
job:
description:
- The name of the target SQL Agent job.
type: str
required: true
description:
description:
- Description for the SQL Agent job.
type: str
required: false
category:
description:
- Category for the target SQL Agent job. Must already exist.
type: str
required: false
enabled:
description:
- Whether the SQL Agent job should be enabled or disabled.
type: bool
required: false
default: true
version_added: '0.4.0'
owner_login:
description:
- The owning login for the database. Will default to the current user if
the database is being created and none supplied.
type: str
required: false
start_step_id:
description:
- What step number the job should begin with when run.
type: int
required: false
schedule:
description:
- The name of the schedule the job should be associated with. Only one schedule per job is supported.
type: str
required: false
force:
description:
- If I(force=true), any job categories will be created if they don't exist already.
type: bool
default: false
author: "John McCall (@lowlydba)"
notes:
- On slower hardware, stale job component data may be returned (i.e., a previous or default job category).
Configuring each component (schedule, step, category, etc.) individually is recommended for this reason.
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create a job
lowlydba.sqlserver.agent_job:
sql_instance: sql-01.myco.io
job: MyJob
force: true
'''
RETURN = r'''
data:
description: Output from the C(New-DbaAgentJob), C(Set-DbaAgentJob), or C(Remove-DbaAgentJob) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,64 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
category = @{type = 'str'; required = $true }
category_type = @{type = 'str'; required = $false; choices = @('LocalJob', 'MultiServerJob', 'None') }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$category = $module.Params.category
$categoryType = $module.Params.category_type
$state = $module.Params.state
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$agentJobCategorySplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Category = $category
EnableException = $true
}
if ($null -ne $categoryType) {
$agentJobCategorySplat.Add("CategoryType", $categoryType)
}
$existingCategory = Get-DbaAgentJobCategory @agentJobCategorySplat
if ($state -eq "present") {
# Create new job category
if ($null -eq $existingCategory) {
$output = New-DbaAgentJobCategory @agentJobCategorySplat -WhatIf:$checkMode
$module.Result.changed = $true
}
}
elseif ($state -eq "absent") {
if ($null -ne $existingCategory) {
$output = $existingCategory | Remove-DbaAgentJobCategory -WhatIf:$checkMode -EnableException -Confirm:$false
$module.Result.changed = $true
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error configuring SQL Agent job category.", $_)
}

View File

@@ -0,0 +1,48 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: agent_job_category
short_description: Configures a SQL Agent job category
description:
- Configures a SQL Agent job category. Creates if it does not exist, else does nothing.
version_added: 0.1.0
options:
category:
description:
- Name of the category.
required: true
type: str
category_type:
description:
- The type of category.
required: false
type: str
choices: ['LocalJob', 'MultiServerJob', 'None']
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create a maintenance job category
lowlydba.sqlserver.agent_job_category:
sql_instance: sql-01.myco.io
category: "Index Maintenance"
'''
RETURN = r'''
data:
description: Output from the C(New-DbaAgentJobCategory) or C(Remove-DbaAgentJobCategory) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,164 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
schedule = @{type = 'str'; required = $true }
job = @{type = 'str'; required = $true }
enabled = @{type = 'bool'; required = $false }
force = @{type = 'bool'; required = $false }
frequency_type = @{type = 'str'; required = $false
choices = @('Once', 'OneTime', 'Daily', 'Weekly', 'Monthly', 'MonthlyRelative', 'AgentStart', 'AutoStart', 'IdleComputer', 'OnIdle')
}
frequency_interval = @{type = 'str'; required = $false; }
frequency_subday_type = @{type = 'str'; required = $false; choices = @('Time', 'Seconds', 'Minutes', 'Hours') }
frequency_subday_interval = @{type = 'int'; required = $false }
frequency_relative_interval = @{type = 'str'; required = $false; choices = @('Unused', 'First', 'Second', 'Third', 'Fourth', 'Last') }
frequency_recurrence_factor = @{type = 'int'; required = $false }
start_date = @{type = 'str'; required = $false }
end_date = @{type = 'str'; required = $false }
start_time = @{type = 'str'; required = $false }
end_time = @{type = 'str'; required = $false }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$schedule = $module.Params.schedule
$job = $module.Params.job
[nullable[bool]]$enabled = $module.Params.enabled
$force = $module.Params.force
$frequencyType = $module.Params.frequency_type
$frequencyInterval = $module.Params.frequency_interval
$frequencySubdayType = $module.Params.frequency_subday_type
[nullable[int]]$frequencySubdayInterval = $module.Params.frequency_subday_interval
$frequencyRelativeInterval = $module.Params.frequency_relative_interval
[nullable[int]]$frequencyRecurrenceFactor = $module.Params.frequency_recurrence_factor
$startDate = $module.Params.start_date
$endDate = $module.Params.end_date
$startTime = $module.Params.start_time
$endTime = $module.Params.end_time
$state = $module.Params.state
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
$scheduleParams = @{
SqlInstance = $SqlInstance
SqlCredential = $sqlCredential
Force = $force
Schedule = $schedule
}
if ($enabled -eq $false) {
$scheduleParams.add("Disabled", $true)
}
if ($null -ne $job) {
$scheduleParams.add("Job", $job)
}
if ($null -ne $startDate) {
$scheduleParams.add("StartDate", $startDate)
}
if ($null -ne $endDate) {
$scheduleParams.add("EndDate", $endDate)
}
if ($null -ne $startTime) {
$scheduleParams.add("StartTime", $startTime)
}
if ($null -ne $endTime) {
$scheduleParams.add("EndTime", $endTime)
}
if ($null -ne $frequencyType) {
$scheduleParams.add("FrequencyType", $frequencyType)
}
if ($null -ne $frequencyInterval) {
$scheduleParams.add("FrequencyInterval", $frequencyInterval)
}
if ($null -ne $frequencySubdayType) {
$scheduleParams.add("FrequencySubdayType", $frequencySubdayType)
}
if ($null -ne $frequencySubdayInterval) {
$scheduleParams.add("FrequencySubdayInterval", $frequencySubdayInterval)
}
if ($null -ne $frequencyRelativeInterval) {
$scheduleParams.add("FrequencyRelativeInterval", $frequencyRelativeInterval)
}
if ($null -ne $frequencyRecurrenceFactor) {
$scheduleParams.add("FrequencyRecurrenceFactor", $frequencyRecurrenceFactor)
}
try {
$existingSchedule = Get-DbaAgentSchedule -SqlInstance $SqlInstance -SqlCredential $sqlCredential -Schedule $schedule
if ($state -eq "present") {
if ($enabled -eq $true) {
$scheduleParams.Add("Enabled", $true)
}
# Update schedule
if ($null -ne $existingSchedule) {
# Need to serialize to prevent SMO auto refreshing
$old = ConvertTo-SerializableObject -InputObject $existingSchedule -UseDefaultProperty $false
$output = Set-DbaAgentSchedule @scheduleParams
if ($null -ne $output) {
$compareProperty = @(
"ActiveEndDate"
"ActiveEndTimeOfDay"
"ActiveEndTimeOfDay"
"ActiveStartTimeOfDay"
"Description"
"FrequencyInterval"
"FrequencyRecurrenceFactor"
"FrequencyRelativeIntervals"
"FrequencySubDayInterval"
"FrequencySubDayTypes"
"FrequencyTypes"
"IsEnabled"
"ScheduleName"
)
$diff = Compare-Object -ReferenceObject $output -DifferenceObject $old -Property $compareProperty
# # Check if schedule was actually changed
# $modifiedSchedule = Get-DbaAgentSchedule -SqlInstance $SqlInstance -SqlCredential $sqlCredential -Schedule $ScheduleName -EnableException
# $scheduleDiff = Compare-Object -ReferenceObject $existingSchedule -DifferenceObject $modifiedSchedule
if ($diff -or $checkMode) {
$module.Result.changed = $true
}
}
}
# Create schedule
else {
$output = New-DbaAgentSchedule @scheduleParams
$module.Result.changed = $true
}
}
elseif ($state -eq "absent") {
# Nothing to remove
if ($null -eq $existingSchedule) {
$module.ExitJson()
}
# Remove schedule
else {
$output = $existingSchedule | Remove-DbaAgentSchedule -Force
$module.Result.changed = $true
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error configuring SQL Agent job schedule.", $_)
}

View File

@@ -0,0 +1,142 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: agent_job_schedule
short_description: Configures a SQL Agent job schedule
description:
- Configures settings for an agent schedule that can be applied to one or more agent jobs.
version_added: 0.1.0
options:
schedule:
description:
- The name of the schedule.
type: str
required: true
job:
description:
- The name of the job that has the schedule.
- Schedules and jobs can also be associated via M(lowlydba.sqlserver.agent_job).
- See U(https://docs.dbatools.io/New-DbaAgentSchedule) for more detailed usage.
type: str
required: true
enabled:
description:
- Whether the schedule is enabled or disabled.
type: bool
required: false
force:
description:
- The force option will ignore some errors in the options and assume defaults.
- It will also remove the any present schedules with the same name for the specific job.
type: bool
frequency_type:
description:
- A value indicating when a job is to be executed.
- If I(force=true) the default will be C(Once).
type: str
required: false
choices: ['Once', 'OneTime', 'Daily', 'Weekly', 'Monthly', 'MonthlyRelative', 'AgentStart', 'AutoStart', 'IdleComputer', 'OnIdle']
frequency_interval:
description:
- The days that a job is executed.
- Allowed values for I(frequency_type=Daily) - C(EveryDay) or a number between C(1) and C(365) inclusive.
- >-
Allowed values for I(frequency_type=Weekly) -
C(Sunday), C(Monday), C(Tuesday), C(Wednesday), C(Thursday), C(Friday), C(Saturday),
C(Weekdays), C(Weekend) or C(EveryDay).
- Allowed values for I(frequency_type=Monthly) - Numbers C(1) through C(31) for each day of the month.
- If C(Weekdays), C(Weekend) or C(EveryDay) is used it overwrites any other value that has been passed before.
- If I(force=true) the default will be C(1).
type: str
required: false
frequency_subday_type:
description:
- Specifies the units for the subday I(frequency_interval).
type: str
required: false
choices: ['Time', 'Seconds', 'Minutes', 'Hours']
frequency_subday_interval:
description:
- The number of subday type periods to occur between each execution of a job.
type: int
required: false
frequency_relative_interval:
description:
- A job's occurrence of I(frequency_interval) in each month. If I(frequency_interval=32) (C(MonthlyRelative)).
type: str
required: false
choices: ['Unused', 'First', 'Second', 'Third', 'Fourth', 'Last']
frequency_recurrence_factor:
description:
- The number of weeks or months between the scheduled execution of a job.
- Required if I(frequency_type=Weekly), I(frequency_type=Monthly) or I(frequency_type=MonthlyRelative).
type: int
required: false
start_date:
description:
- The date on which execution of a job can begin.
- If I(force=true)the start date will be the current day.
- Format is C(YYYY-MM-DD).
type: str
required: false
end_date:
description:
- The date on which execution of a job can stop.
- If I(force=true) the end date will be C(9999-12-31).
- Format is C(YYYY-MM-DD).
type: str
required: false
start_time:
description:
- The time on any day to begin execution of a job. Format C(HHMMSS) (24 hour clock).
- If I(force=true) the start time will be C(00:00:00).
type: str
required: false
end_time:
description:
- The time on any day to end execution of a job. Format C(HHMMSS) (24 hour clock).
- If (force=true) the start time will be C(23:59:59).
type: str
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create a job schedule
lowlydba.sqlserver.agent_job_schedule:
sql_instance: sql-01.myco.io
schedule: DailySchedule
force: true
enabled: true
start_date: 2020-05-25 # May 25, 2020
end_date: 2099-05-25 # May 25, 2099
start_time: 010500 # 01:05:00 AM
end_time: 140030 # 02:00:30 PM
state: present
- name: Create a job with schedule
lowlydba.sqlserver.agent_job:
sql_instance: sql-01.myco.io
job: MyJob
force: true
schedule: DailySchedule
'''
RETURN = r'''
data:
description: Output from the C(New-DbaAgentJobSchedule) or C(Remove-DbaAgentJobSchedule) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,157 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
job = @{type = 'str'; required = $true }
step_id = @{type = 'int'; required = $false }
step_name = @{type = 'str'; required = $false }
database = @{type = 'str'; required = $false; default = 'master' }
subsystem = @{type = 'str'; required = $false; default = 'TransactSql'
choices = @('CmdExec', 'Distribution', 'LogReader', 'Merge', 'PowerShell', 'QueueReader', 'Snapshot', 'Ssis', 'TransactSql')
}
command = @{type = 'str'; required = $false }
on_success_action = @{type = 'str'; required = $false; default = 'QuitWithSuccess'
choices = @('QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep')
}
on_success_step_id = @{type = 'int'; required = $false; default = 0 }
on_fail_action = @{type = 'str'; required = $false; default = 'QuitWithFailure'
choices = @('QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep')
}
on_fail_step_id = @{type = 'int'; required = $false; default = 0 }
retry_attempts = @{type = 'int'; required = $false; default = 0 }
retry_interval = @{type = 'int'; required = $false; default = 0 }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
required_together = @(
, @('retry_attempts', 'retry_interval')
)
required_one_of = @(
, @('step_id', 'step_name')
)
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$job = $module.Params.job
$stepId = $module.Params.step_id
$stepName = $module.Params.step_name
$database = $module.Params.database
$subsystem = $module.Params.subsystem
$command = $module.Params.command
$onSuccessAction = $module.Params.on_success_action
[nullable[int]]$onSuccessStepId = $module.Params.on_success_step_id
$onFailAction = $module.Params.on_fail_action
[nullable[int]]$onFailStepId = $module.Params.on_fail_step_id
[int]$retryAttempts = $module.Params.retry_attempts
[nullable[int]]$retryInterval = $module.Params.retry_interval
$state = $module.Params.state
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
# Configure Agent job step
try {
$existingJobSteps = Get-DbaAgentJobStep -SqlInstance $SqlInstance -SqlCredential $sqlCredential -Job $job
$existingJobStep = $existingJobSteps | Where-Object Name -eq $stepName
if ($state -eq "absent") {
if ($null -eq $existingJobStep) {
# try fetching name by id if we only care about removing
$existingJobStep = $existingJobSteps | Where-Object Id -eq $stepId
$stepName = $existingJobStep.Name
}
if ($existingJobStep) {
$removeStepSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Job = $job
StepName = $stepName
}
$output = Remove-DbaAgentJobStep @removeStepSplat
$module.Result.changed = $true
}
}
elseif ($state -eq "present") {
if (!($stepName) -or !($stepId)) {
$module.FailJson("Step name must be specified when state=present.")
}
$jobStepParams = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Job = $job
StepName = $stepName
Database = $database
SubSystem = $subsystem
OnSuccessAction = $onSuccessAction
OnSuccessStepId = $onSuccessStepId
OnFailAction = $onFailAction
OnFailStepId = $onFailStepId
RetryAttempts = $retryAttempts
RetryInterval = $retryInterval
WhatIf = $checkMode
}
if ($null -ne $command) {
$jobStepParams.Add("Command", $command)
}
# No existing job step
if ($null -eq $existingJobStep) {
$jobStepParams.Add("StepId", $stepId)
$output = New-DbaAgentJobStep @jobStepParams
$module.Result.changed = $true
}
# Update existing
else {
# Validate step name isn't taken already - must be unique within a job
if ($existingJobStep.Name -eq $StepName -and $existingJobStep.ID -ne $stepId) {
$module.FailJson("There is already a step named '$StepName' for this job with an ID of $($existingJobStep.ID).")
}
# Reference by old name in case new name differs for step id
$jobStepParams.StepName = $existingJobStep.Name
$jobStepParams.Add("NewName", $StepName)
# Need to serialize to prevent SMO auto refreshing
$old = ConvertTo-SerializableObject -InputObject $existingJobStep -UseDefaultProperty $false
$output = Set-DbaAgentJobStep @jobStepParams
if ($null -ne $output) {
$compareProperty = @(
"Name"
"DatabaseName"
"Command"
"Subsystem"
"OnFailAction"
"OnFailActionStep"
"OnSuccessAction"
"OnSuccessActionStep"
"RetryAttempts"
"RetryInterval"
)
$diff = Compare-Object -ReferenceObject $output -DifferenceObject $old -Property $compareProperty
}
if ($diff -or $checkMode) {
$module.Result.changed = $true
}
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error configuring SQL Agent job step.", $_)
}

View File

@@ -0,0 +1,118 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: agent_job_step
short_description: Configures a SQL Agent job step
description:
- Configures a step for an agent job.
version_added: 0.1.0
options:
job:
description:
- The name of the job to which to add the step.
required: true
type: str
step_id:
description:
- The sequence identification number for the job step. Step identification numbers start at C(1) and increment without gaps.
- Required if I(state=present).
required: false
type: int
step_name:
description:
- The name of the step. Required if I(state=present).
required: false
type: str
database:
description:
- The name of the database in which to execute a Transact-SQL step.
required: false
type: str
default: 'master'
subsystem:
description:
- The subsystem used by the SQL Server Agent service to execute command.
required: false
type: str
default: 'TransactSql'
choices: ['CmdExec', 'Distribution', 'LogReader', 'Merge', 'PowerShell', 'QueueReader', 'Snapshot', 'Ssis', 'TransactSql']
command:
description:
- The commands to be executed by SQLServerAgent service through subsystem.
required: false
type: str
on_success_action:
description:
- The action to perform if the step succeeds.
required: false
type: str
default: 'QuitWithSuccess'
choices: ['QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep']
on_success_step_id:
description:
- The ID of the step in this job to execute if the step succeeds and I(on_success_action=GoToStep).
required: false
type: int
default: 0
on_fail_action:
description:
- The action to perform if the step fails.
required: false
type: str
default: 'QuitWithFailure'
choices: ['QuitWithSuccess', 'QuitWithFailure', 'GoToNextStep', 'GoToStep']
on_fail_step_id:
description:
- The ID of the step in this job to execute if the step fails and I(on_fail_action=GoToStep).
required: false
type: int
default: 0
retry_attempts:
description:
- The number of retry attempts to use if this step fails. The default is C(0).
required: false
type: int
default: 0
retry_interval:
description:
- The amount of time in minutes between retry attempts.
required: false
type: int
default: 0
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create a job
lowlydba.sqlserver.agent_job:
sql_instance: sql-01.myco.io
job: MyJob
force: true
- name: Create a job step
lowlydba.sqlserver.agent_job_step:
sql_instance: sql-01.myco.io
job: MyJob
step_name: Step1
step_id: 1
command: "TRUNCATE TABLE dbo.TestData;"
'''
RETURN = r'''
data:
description: Output from the C(New-DbaAgentJobStep), C(Set-DbaAgentJobStep), or C(Remove-DbaAgentJobStep) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,235 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
sql_instance_secondary = @{type = "str"; required = $false }
sql_username_secondary = @{type = 'str'; required = $false }
sql_password_secondary = @{type = 'str'; required = $false; no_log = $true }
database = @{type = "str"; required = $false; aliases = @('database_name') }
ag_name = @{type = "str"; required = $true }
all_ags = @{type = "bool"; required = $false; }
shared_path = @{type = "str"; required = $false; default = $null }
dtc_support_enabled = @{type = "bool"; required = $false; }
basic_availability_group = @{type = "bool"; required = $false; }
database_health_trigger = @{type = "bool"; required = $false; }
is_distributed_ag = @{type = "bool"; required = $false; }
use_last_backup = @{type = "bool"; required = $false; }
healthcheck_timeout = @{type = "int"; required = $false; }
availability_mode = @{
type = "str"
required = $false
default = "SynchronousCommit"
choices = @("SynchronousCommit", "AsynchronousCommit")
}
failure_condition_level = @{
type = "str"
required = $false
choices = @(
"OnAnyQualifiedFailureCondition",
"OnCriticalServerErrors",
"OnModerateServerErrors",
"OnServerDown",
"OnServerUnresponsive"
)
}
failover_mode = @{
type = "str"
required = $false
default = "Automatic"
choices = @("Manual", "Automatic")
}
seeding_mode = @{
type = "str"
required = $false
default = "Manual"
choices = @("Manual", "Automatic")
}
automated_backup_preference = @{
type = "str"
required = $false
default = "Secondary"
choices = @("None", "Primary", "Secondary", "SecondaryOnly")
}
cluster_type = @{
type = "str"
required = $false
default = "Wsfc"
choices = @("Wsfc", "External", "None")
}
allow_null_backup = @{type = "bool"; required = $false }
force = @{type = "bool"; required = $false }
state = @{type = "str"; required = $false; default = "present"; choices = @("present", "absent") }
}
required_together = @(
, @('sql_username_secondary', 'sql_password_secondary')
)
}
# Setup var
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$ProgressPreference = "SilentlyContinue"
# Var
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$secondary = $module.Params.sql_instance_secondary
if ($null -ne $module.Params.sql_username_secondary) {
[securestring]$secondarySecPassword = ConvertTo-SecureString $Module.Params.sql_password_secondary -AsPlainText -Force
[pscredential]$secondarySqlCredential = New-Object System.Management.Automation.PSCredential ($Module.Params.sql_username_secondary, $secondarySecPassword)
}
$agName = $module.Params.ag_name
$database = $module.Params.database
$seedingMode = $module.Params.seeding_mode
$sharedPath = $module.Params.shared_path
$healthCheckTimeout = $module.Params.healthcheck_timeout
$availabilityMode = $module.Params.availability_mode
$failureConditionLevel = $module.Params.failure_condition_level
$failoverMode = $module.Params.failover_mode
$automatedBackupPreference = $module.Params.automated_backup_preference
$clusterType = $module.Params.cluster_type
$state = $module.Params.state
[nullable[bool]]$all_ags = $module.Params.all_ags
[nullable[bool]]$useLastBackup = $module.Params.use_last_backup
[nullable[bool]]$dtcSupportEnabled = $module.Params.dtc_support_enabled
[nullable[bool]]$basicAvailabilityGroup = $module.Params.basic_availability_group
[nullable[bool]]$databaseHealthTrigger = $module.Params.database_health_trigger
[nullable[bool]]$isDistributedAg = $module.Params.is_distributed_ag
[nullable[bool]]$force = $module.Params.force
[nullable[bool]]$allowNullBackup = $module.Params.allow_null_backup
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
try {
$existingAG = Get-DbaAvailabilityGroup -SqlInstance $sqlInstance -SqlCredential $sqlCredential -AvailabilityGroup $agName
if ($state -eq "present") {
$agSplat = @{
Primary = $sqlInstance
PrimarySqlCredential = $sqlCredential
Name = $agName
SeedingMode = $seedingMode
FailoverMode = $failoverMode
AvailabilityMode = $availabilityMode
AutomatedBackupPreference = $automatedBackupPreference
ClusterType = $clusterType
}
if ($null -ne $sharedPath -and $seedingMode -eq "Manual") {
$agSplat.Add("SharedPath", $sharedPath)
}
if ($useLastBackup -eq $true) {
$agSplat.Add("UseLastBackup", $useLastBackup)
}
if ($dtcSupportEnabled -eq $true) {
$agSplat.Add("DtcSupport", $dtcSupportEnabled)
}
if ($basicAvailabilityGroup -eq $true) {
$agSplat.Add("Basic", $basicAvailabilityGroup)
}
if ($databaseHealthTrigger -eq $true) {
$agSplat.Add("DatabaseHealthTrigger", $databaseHealthTrigger)
}
if ($null -ne $healthCheckTimeout) {
$agSplat.Add("HealthCheckTimeout", $healthCheckTimeout)
}
if ($null -ne $failureConditionLevel) {
$agSplat.Add("FailureConditionLevel", $failureConditionLevel)
}
if ($null -ne $database) {
$agSplat.Add("Database", $database)
}
if ($null -ne $secondary) {
$agSplat.Add("Secondary", $secondary)
}
if ($null -ne $secondarySqlCredential) {
$agSplat.Add("SecondarySqlCredential", $secondarySqlCredential)
}
if ($force -eq $true) {
$agSplat.Add("Force", $force)
}
# Create the AG with initial replica(s)
if ($null -eq $existingAG) {
# Full backup requirement for new AG via automatic seeding
if ($seedingMode -eq "automatic" -and $null -ne $database) {
$dbBackup = Get-DbaLastBackup -SqlInstance $sqlInstance -SqlCredential $sqlCredential -Database $database
if ($null -eq $dbBackup.LastFullBackup -and $allowNullBackup -eq $true) {
$backupSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
FilePath = "NUL"
Type = "Full"
}
$null = Backup-DbaDatabase @backupSplat
}
}
$output = New-DbaAvailabilityGroup @agSplat
$module.Result.changed = $true
}
# Configure existing AG
else {
$setAgSplat = @{
AutomatedBackupPreference = $automatedBackupPreference
ClusterType = $clusterType
}
if ($all_ags -eq $true) {
$setAgSplat.Add("AllAvailabilityGroups", $all_ags)
}
if ($dtcSupportEnabled -eq $true) {
$setAgSplat.Add("DtcSupportEnabled", $dtcSupportEnabled)
}
if ($basicAvailabilityGroup -eq $true) {
$setAgSplat.Add("BasicAvailabilityGroup", $basicAvailabilityGroup)
}
if ($databaseHealthTrigger -eq $true) {
$setAgSplat.Add("DatabaseHealthTrigger", $databaseHealthTrigger)
}
if ($null -ne $failureConditionLevel) {
$setAgSplat.Add("FailureConditionLevel", $failureConditionLevel)
}
if ($null -ne $healthCheckTimeout) {
$setAgSplat.Add("HealthCheckTimeout", $healthCheckTimeout)
}
if ($isDistributedAg -eq $true) {
$setAgSplat.Add("IsDistributedAvailabilityGroup", $isDistributedAg)
}
$compareProperty = ($existingAG.Properties | Where-Object Name -in $setAgSplat.Keys).Name
$agDiff = Compare-Object -ReferenceObject $existingAG -DifferenceObject $setAgSplat -Property $compareProperty
if ($null -ne $agDiff) {
$output = $existingAG | Set-DbaAvailabilityGroup @setAgSplat
$module.Result.changed = $true
}
}
}
elseif ($state -eq "absent") {
if ($null -ne $existingAG) {
if ($all_ags -eq $true) {
$existingAG | Remove-DbaAvailabilityGroup -AllAvailabilityGroups
}
else {
$existingAG | Remove-DbaAvailabilityGroup
}
$module.Result.changed = $true
}
}
if ($output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Configuring Availability Group failed: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,157 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: availability_group
short_description: Configures availability group(s)
description:
- Configures SQL Server Availability Group(s) with up to one replica.
version_added: 0.4.0
options:
sql_instance_secondary:
description:
- The secondary SQL Server instance for the new Availability Group.
type: str
required: false
sql_username_secondary:
description:
- Username for SQL Authentication for the secondary replica.
type: str
required: false
sql_password_secondary:
description:
- Password for SQL Authentication for the secondary replica.
type: str
required: false
database:
description:
- Name of the database to create the Availability Group for.
type: str
required: false
aliases:
- database_name
ag_name:
description:
- Name of the Availability Group.
type: str
required: true
all_ags:
description:
- Apply changes to all availability groups on the instance. Only used for configuring existing availability groups.
type: bool
required: false
shared_path:
description:
- The network share where the backups will be backed up and restored from.
type: str
required: false
dtc_support_enabled:
description:
- Enables Dtc support.
type: bool
required: false
basic_availability_group:
description:
- Indicates whether the availability group is Basic Availability Group.
type: bool
required: false
database_health_trigger:
description:
- Indicates whether the availability group triggers the database health.
type: bool
required: false
is_distributed_ag:
description:
- Indicates whether the availability group is distributed.
type: bool
required: false
healthcheck_timeout:
description:
- This setting used to specify the length of time, in milliseconds,
that the SQL Server resource DLL should wait for information returned by the C(sp_server_diagnostics)
stored procedure before reporting the Always On Failover Cluster Instance (FCI) as unresponsive.
- Changes that are made to the timeout settings are effective immediately and do not require a restart of the SQL Server resource.
type: int
required: false
failure_condition_level:
description:
- Specifies the different conditions that can trigger an automatic failover in Availability Group.
type: str
required: false
choices: ['OnAnyQualifiedFailureCondition', 'OnCriticalServerErrors', 'OnModerateServerErrors', 'OnServerDown', 'OnServerUnresponsive']
cluster_type:
description:
- Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.
type: str
required: false
default: 'Wsfc'
choices: ['Wsfc', 'External', 'None']
failover_mode:
description:
- Whether the replica have Automatic or Manual failover.
type: str
required: false
default: 'Automatic'
choices: ['Automatic', 'Manual']
availability_mode:
description:
- Whether the replica should be Asynchronous or Synchronous.
- Only used in creating a new availability group.
type: str
required: false
default: 'SynchronousCommit'
choices: ['AsynchronousCommit', 'SynchronousCommit']
seeding_mode:
description:
- Default seeding mode for the replica. Should remain as the default otherwise manual setup may be required.
type: str
required: false
default: 'Manual'
choices: ['Automatic', 'Manual']
automated_backup_preference:
description:
- How to handle backup requests by default.
type: str
required: false
default: 'Secondary'
choices: ['None', 'Primary', 'Secondary', 'SecondaryOnly']
allow_null_backup:
description:
- Allow taking a full backup to C(NULL) if one does not exist and I(seeding_mode=Automatic).
type: bool
required: false
force:
description:
- Drop and recreate the database on remote servers using fresh backup.
type: bool
use_last_backup:
description:
- Use the last full and log backup of database. A log backup must be the last backup.
type: bool
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create Availability Group
lowlydba.sqlserver.availability_group:
sql_instance: sql-01.myco.io
ag_name: AG_MyDatabase
'''
RETURN = r'''
data:
description: Output from the C(New-DbaAvailabilityGroup) or C(Set-DbaAvailabilityGroup) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,138 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
database = @{type = 'str'; required = $true }
path = @{type = 'str'; required = $false }
file_path = @{type = 'str'; required = $false }
increment_prefix = @{type = 'bool'; required = $false; default = $false }
replace_in_name = @{type = 'bool'; required = $false; default = $false }
copy_only = @{type = 'bool'; required = $false; default = $false }
type = @{type = 'str'; required = $false; default = 'database'; choices = @('full', 'log', 'differential', 'diff', 'database') }
timestamp_format = @{type = 'str'; required = $false }
encryption_certificate = @{type = 'str'; required = $false }
encryption_algorithm = @{type = 'str'; required = $false; choices = @('AES128', 'AES192', 'AES256', 'TRIPLEDES') }
create_folder = @{type = 'bool'; required = $false; default = $false }
file_count = @{type = 'int'; required = $false; default = 0 }
compress = @{type = 'bool'; required = $false; default = $false }
checksum = @{type = 'bool'; required = $false; default = $false }
verify = @{type = 'bool'; required = $false; default = $false }
no_recovery = @{type = 'bool'; required = $false; default = $false }
build_path = @{type = 'bool'; required = $false; default = $false }
max_transfer_size = @{type = 'int'; required = $false; default = 0 }
with_format = @{type = 'bool'; required = $false; default = $false }
initialize = @{type = 'bool'; required = $false; default = $false }
ignore_file_checks = @{type = 'bool'; required = $false; default = $false }
block_size = @{type = 'str'; required = $false; choices = @('0.5kb', '1kb', '2kb', '4kb', '8kb', '16kb', '32kb', '64kb') }
buffer_count = @{type = 'int'; required = $false; default = 0 }
azure_base_url = @{type = 'str'; required = $false }
azure_credential = @{type = 'str'; required = $false }
}
mutually_exclusive = @(
, @('path', 'azure_base_url')
)
required_together = @(
, @('encryption_algorithm', 'encryption_certificate')
)
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$path = $module.Params.path
$filePath = $module.Params.file_path
$incrementPrefix = $module.Params.increment_prefix
$replaceInName = $module.Params.replace_in_name
$copyOnly = $module.Params.copy_only
$type = $module.Params.type
$createFolder = $module.Params.create_folder
$fileCount = $module.Params.file_count
$compressBackup = $module.Params.compress_backup
$checkSum = $module.Params.checksum
$verify = $module.Params.verify
$maxTransferSize = $module.Params.max_transfer_size
$blockSize = $module.Params.block_size
$bufferCount = $module.Params.buffer_count
$noRecovery = $module.Params.no_recovery
$buildPath = $module.Params.build_path
$withFormat = $module.Params.with_format
$initialize = $module.Params.initialize
$timestampFormat = $module.Params.timestamp_format
$ignoreFileChecks = $module.Params.ignore_file_checks
$encryptionAlgorithm = $module.Params.encryption_algorithm
$encryptionCertificate = $modules.Params.encryption_certificate
$azureBaseUrl = $modules.Params.azure_base_url
$azureCredential = $modules.Param.azure_credential
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
try {
$backupSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
IncrementPrefix = $incrementPrefix
ReplaceInName = $replaceInName
CopyOnly = $copyOnly
Type = $type
CreateFolder = $createFolder
FileCount = $fileCount
CompressBackup = $compressBackup
Checksum = $checkSum
Verify = $verify
MaxTransferSize = $maxTransferSize
BufferCount = $bufferCount
NoRecovery = $noRecovery
BuildPath = $buildPath
WithFormat = $withFormat
Initialize = $initialize
IgnoreFileChecks = $ignoreFileChecks
}
if ($null -ne $path) {
$backupSplat.Add("Path", $path)
}
if ($null -ne $filePath) {
$backupSplat.Add("FilePath", $filePath)
}
if ($null -ne $blockSize) {
$backupSplat.Add("BlockSize", ($blockSize / 1))
}
if ($null -ne $timestampFormat) {
$backupSplat.Add("TimestampFormat", $timestampFormat)
}
if ($null -ne $encryptionAlgorithm) {
$backupSplat.Add("EncryptionAlgorithm", $encryptionAlgorithm)
}
if ($null -ne $encryptionCertificate) {
$backupSplat.Add("EncryptionCertificate", $encryptionCertificate)
}
if ($null -ne $azureBaseUrl) {
$backupSplat.Add("AzureBaseURL", $azureBaseUrl)
}
if ($null -ne $azureCredential) {
$backupSplat.Add("AzureCredential", $azureCredential)
}
$output = Backup-DbaDatabase @backupSplat
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
$module.Result.changed = $true
}
$module.ExitJson()
}
catch {
$module.FailJson("Error backing up database: $($_.Exception.Message).", $_)
}

View File

@@ -0,0 +1,197 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: backup
short_description: Performs a backup operation
description:
- Performs any type of database backup operation.
version_added: 0.8.0
options:
database:
description:
- The database to process.
type: str
required: true
path:
description:
- Path in which to place the backup files.
- If not specified, the backups will be placed in the default backup location for SqlInstance.
type: str
required: false
file_path:
description:
- The name of the file to backup to.
- If no name is specified then the backup files will be named C(DatabaseName_yyyyMMddHHmm) (i.e. C(Database1_201714022131))
type: str
required: false
increment_prefix:
description:
- If set, this will prefix backup files with an incrementing integer (ie; C(1-), C(2-)).
- Using this has been alleged to improved restore times on some Azure based SQL Database platforms.
type: bool
required: false
default: false
replace_in_name:
description:
- If set, the following list of strings will be replaced in the FilePath and Path strings.
C(instancename) - will be replaced with the instance Name
C(servername) - will be replaced with the server name
C(dbname) - will be replaced with the database name
C(timestamp) - will be replaced with the timestamp (either the default, or the format provided)
C(backuptype) - will be replaced with C(Full), C(Log), or C(Differential) as appropriate
type: bool
required: false
default: false
copy_only:
description:
- The backup will be CopyOnly.
type: bool
required: false
default: false
type:
description:
- The type of backup to perform.
type: str
required: false
default: 'database'
choices: ['full', 'log', 'differential', 'diff', 'database']
create_folder:
description:
- If set, database is backed up to its own subfolder within the path.
type: bool
required: false
default: false
file_count:
description:
- The number of striped files to create the backup with.
type: int
required: false
default: 0
compress:
description:
- If set, use compression when creating the backup if it is supported by the version and edition.
type: bool
required: false
default: false
checksum:
description:
- If set, the backup checksum will be calculated.
type: bool
required: false
default: false
verify:
description:
- If set, the backup will be verified via C(RESTORE VERIFYONLY)
type: bool
required: false
default: false
max_transfer_size:
description:
- Sets the size of the unit of transfer. Values must be a multiple of 64kb.
type: int
required: false
default: 0
block_size:
description:
- Specifies block size to use.
type: str
required: false
choices: ['0.5kb','1kb','2kb','4kb','8kb','16kb','32kb','64kb']
buffer_count:
description:
- Number of I/O buffers to use.
type: int
required: false
default: 0
azure_base_url:
description:
- The URL to the base container of an Azure Storage account to write backups to.
type: str
required: false
azure_credential:
description:
- The name of the credential on the SQL instance that can write to the I(azure_base_url),
only needed if using Storage access keys If using SAS credentials, the command will look for a credential with a name matching the I(azure_base_url).
type: str
required: false
no_recovery:
description:
- If set, performs a tail log backup.
type: bool
required: false
default: false
build_path:
description:
- By default this command will not attempt to create missing paths, this switch will change the behaviour so that it will.
type: bool
required: false
default: false
with_format:
description:
- Formats the media as the first step of the backup operation.
type: bool
required: false
default: false
initialize:
description:
- Initializes the media as part of the backup operation.
type: bool
required: false
default: false
timestamp_format:
description:
- By default the command timestamps backups using the format C(yyyyMMddHHmm). Using this option this can be overridden.
type: str
required: false
ignore_file_checks:
description:
- If set, stops the function from checking path validity.
type: bool
required: false
default: false
encryption_algorithm:
description:
- Specifies the Encryption Algorithm to used.
type: str
required: false
choices: ['AES128','AES192','AES256','TRIPLEDES']
encryption_certificate:
description:
- The name of the certificate to be used to encrypt the backups.
type: str
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Create striped full database backup in default dir
lowlydba.sqlserver.backup:
sql_instance: sql-01.myco.io
database: LowlyDB
type: full
file_count: 8
- name: Create t-log backup
lowlydba.sqlserver.backup:
sql_instance: sql-01.myco.io
database: LowlyDB
type: log
'''
RETURN = r'''
data:
description: Modified output from the C(Backup-DbaDatabase) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,117 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
identity = @{type = 'str'; required = $true }
name = @{type = 'str'; required = $false }
password = @{type = 'str'; required = $false; no_log = $true }
mapped_class_type = @{type = 'str'; required = $false; choices = @('CryptographicProvider', 'None') }
provider_name = @{type = 'str'; required = $false }
force = @{type = 'bool'; required = $false; default = $false }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$identity = $module.Params.identity
$name = $module.Params.name
if ($null -ne $module.Params.password) {
$secure_password = ConvertTo-SecureString -String $module.Params.password -AsPlainText -Force
}
$mapped_class_type = $module.Params.mapped_class_type
$provider_name = $module.Params.provider_name
$state = $module.Params.state
$force = $module.Params.force
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$getCredendtialSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Identity = $identity
EnableException = $true
}
$existingCredential = Get-DbaCredential @getCredendtialSplat
if ($state -eq "absent") {
# Remove credential if it exists
if ($null -ne $existingCredential) {
try {
$removeCredentialSplat = @{
EnableException = $true
WhatIf = $checkMode
Confirm = $false
}
$output = $existingCredential | Remove-DbaCredential @removeCredentialSplat
$module.Result.changed = $true
}
catch {
$module.FailJson("Removing credential failed: $($_.Exception.Message)", $_)
}
}
}
elseif ($state -eq "present") {
# Create credential
if (($null -ne $existingCredential -and $force -eq $true) -or $null -eq $existingCredential) {
try {
$newCredentialSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Identity = $identity
EnableException = $true
WhatIf = $checkMode
Force = $force
Confirm = $false
}
if ($null -ne $name) {
$newCredentialSplat.Add("Name", $name)
}
if ($null -ne $secure_password) {
$newCredentialSplat.Add("SecurePassword", $secure_password)
}
if ($null -ne $mapped_class_type) {
$newCredentialSplat.Add("MappedClassType", $mapped_class_type)
}
if ($null -ne $provider_name) {
$newCredentialSplat.Add("ProviderName", $provider_name)
}
$output = New-DbaCredential @newCredentialSplat
$module.result.changed = $true
}
catch {
$module.FailJson("Creating credential failed: $($_.Exception.Message)", $_)
}
}
# Return existing credential if nothing is changed
elseif ($null -ne $existingCredential) {
$output = $existingCredential
}
}
try {
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Failure: $($_.Exception.Message)", $_)
}
}
catch {
$module.FailJson("Configuring credential failed: $($_.Exception.Message) ; $getCredendtialSplat", $_)
}

View File

@@ -0,0 +1,91 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: credential
short_description: Configures a credential on a SQL server
description:
- Creates, replaces, or removes a credential on a SQL server.
version_added: 1.3.0
options:
identity:
description:
- The Credential Identity.
type: str
required: true
name:
description:
- The Credential name.
type: str
required: false
password:
description:
- Password used to authenticate the Credential Identity.
type: str
required: false
mapped_class_type:
description:
- Sets the class associated with the credential.
type: str
required: false
choices: ['CryptographicProvider','None']
provider_name:
description:
- Specifies the cryptographic provider name for the Enterprise Key Management Provider.
type: str
required: false
force:
description:
- If this switch is enabled, the existing credential will be dropped and recreated.
type: bool
default: false
author:
- "Joe Krilov (@Joey40)"
- "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create a credential with a password
lowlydba.sqlserver.credential:
sql_instance: sql-01.myco.io
identity: ad\\user
name: MyCredential
password : <Password>
- name: Replace an existing credential
lowlydba.sqlserver.credential:
sql_instance: sql-01.myco.io
identity: MyIdentity
force: true
- name: Create a credential using a SAS token for a backup URL
lowlydba.sqlserver.credential:
sql_instance: sql-01.myco.io
identity: SHARED ACCESS SIGNATURE
name: https://<azure storage account name>.blob.core.windows.net/<blob container>
password : <Shared Access Token>
- name: Remove a credential
lowlydba.sqlserver.credential:
sql_instance: sql-01.myco.io
identity: MyIdentity
state: absent
'''
RETURN = r'''
data:
description: Output from the C(New-DbaDbCredential), C(Get-DbaDbCredential), or C(Remove-DbaDbCredential) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,242 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
database = @{type = 'str'; required = $true }
recovery_model = @{type = 'str'; required = $false; choices = @('Full', 'Simple', 'BulkLogged') }
data_file_path = @{type = 'str'; required = $false }
log_file_path = @{type = 'str'; required = $false }
owner = @{type = 'str'; required = $false; }
maxdop = @{type = 'int'; required = $false; }
secondary_maxdop = @{type = 'int'; required = $false; }
compatibility = @{type = 'str'; required = $false; }
rcsi = @{type = 'bool'; required = $false; }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$recoveryModel = $module.Params.recovery_model
$dataFilePath = $module.Params.data_file_path
$logFilePath = $module.Params.log_file_path
$owner = $module.Params.owner
$compatibility = $module.Params.compatibility
[nullable[bool]]$rcsiEnabled = $module.Params.rcsi
[nullable[int]]$maxDop = $module.Params.maxdop
[nullable[int]]$secondaryMaxDop = $module.Params.secondary_maxdop
$state = $module.Params.state
$checkMode = $module.CheckMode
try {
# Get database status
try {
$server = Connect-DbaInstance -SqlInstance $sqlInstance -SqlCredential $sqlCredential
$getDatabaseSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
OnlyAccessible = $true
ExcludeSystem = $true
EnableException = $true
}
$existingDatabase = Get-DbaDatabase @getDatabaseSplat
$output = $existingDatabase
}
catch {
$module.FailJson("Error checking database status.", $_.Exception.Message)
}
if ($state -eq "absent") {
if ($null -ne $existingDatabase) {
$existingDatabase | Remove-DbaDatabase -WhatIf:$checkMode -EnableException -Confirm:$false
$module.Result.changed = $true
}
$module.ExitJson()
}
elseif ($state -eq "present") {
# Create database
if ($null -eq $existingDatabase) {
try {
$newDbParams = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
WhatIf = $checkMode
EnableException = $true
}
if ($null -ne $dataFilePath) {
$newDbParams.Add("DataFilePath", $dataFilePath)
}
if ($null -ne $logFilePath) {
$newDbParams.Add("LogFilePath", $logFilePath)
}
if ($null -ne $owner) {
$newDbParams.Add("Owner", $owner)
}
$output = New-DbaDatabase @newDbParams
$module.Result.changed = $true
}
catch {
$module.FailJson("Creating database [$database] failed.", $_)
}
}
# Set Owner
elseif ($null -ne $owner) {
try {
if ($existingDatabase.Owner -ne $owner) {
$setDbParams = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
TargetLogin = $owner
WhatIf = $checkMode
EnableException = $true
}
$null = Set-DbaDbOwner @setDbParams
$output = Get-DbaDatabase @getDatabaseSplat
$module.Result.changed = $true
}
}
catch {
$module.FailJson("Setting database owner for [$database] failed.", $_)
}
}
# Add non-standard fields to output
if ($null -ne $output) {
# Secondary MaxDop
[int]$existingSecondaryMaxDop = $server.Databases[$database].SecondaryMaxDop
$output | Add-Member -MemberType NoteProperty -Name "SecondaryMaxDop" -Value $existingSecondaryMaxDop
$output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("SecondaryMaxDop")
# MaxDop (exists, but is not in default display)
$existingMaxDop = $server.Databases[$database].MaxDop
$output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("MaxDop")
# RCSI
$existingRCSI = $server.Databases[$database].IsReadCommittedSnapshotOn
$output | Add-Member -MemberType NoteProperty -Name "RCSI" -Value $existingRCSI
$output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("RCSI")
}
# Recovery Model
if ($null -ne $recoveryModel) {
try {
if ($recoveryModel -ne $output.RecoveryModel) {
$recoveryModelSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
RecoveryModel = $recoveryModel
WhatIf = $checkMode
EnableException = $true
Confirm = $false
}
$null = Set-DbaDbRecoveryModel @recoveryModelSplat
$output.RecoveryModel = $recoveryModel
$module.Result.changed = $true
}
}
catch {
$module.FailJson("Setting recovery model for [$database] failed.", $_)
}
}
# Compatibility Mode
if ($null -ne $compatibility) {
try {
$existingCompatibility = $output.Compatibility
if ($compatibility -ne $existingCompatibility) {
$compatSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
Compatibility = $compatibility
WhatIf = $checkMode
EnableException = $true
}
$null = Set-DbaDbCompatibility @compatSplat
$output.Compatibility = $compatibility
$module.Result.changed = $true
}
}
catch {
$module.FailJson("Setting Compatibility for [$database] failed.", $_)
}
}
# RCSI
if ($null -ne $rcsiEnabled) {
try {
if ($rcsiEnabled -ne $existingRCSI) {
if (-not $checkMode) {
$server.Databases[$database].IsReadCommittedSnapshotOn = $rcsiEnabled
$server.Databases[$database].Alter()
$output.RCSI = $rcsiEnabled
}
$module.Result.changed = $true
}
}
catch {
$module.FailJson("Setting Read Commmitted Snapshot Isolation for [$database] failed.", $_)
}
}
# Configure MAXDOPs
## Database Scoped MaxDop
if ($null -ne $MaxDop) {
try {
if ($MaxDop -ne $existingMaxDop) {
if (-not $checkMode) {
$server.Databases[$database].MaxDop = $maxDop
$server.Databases[$database].Alter()
$output.MaxDop = $MaxDOP
}
$module.Result.changed = $true
}
}
catch {
$module.FailJson("Setting MAXDOP for [$database] failed.", $_)
}
}
## Secondary Mode MaxDop
if ($null -ne $secondaryMaxDOP) {
try {
if ($secondaryMaxDop -ne $existingSecondaryMaxDop) {
if (-not $checkMode) {
$server.Databases[$database].MaxDopForSecondary = $secondaryMaxDOP
$server.Databases[$database].Alter()
$output.SecondaryMaxDop = $secondaryMaxDop
}
$module.Result.changed = $true
}
}
catch {
$module.FailJson("Setting MaxDop for secondary mode failed.", $_)
}
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Configuring database failed: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,94 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: database
short_description: Creates and configures a database
description:
- Adds a new database to an existing SQL Server instance.
version_added: 0.1.0
options:
database:
description:
- Name of the target database.
type: str
required: true
recovery_model:
description:
- Choose the recovery model for the database.
type: str
required: false
choices: ['Full', 'Simple', 'BulkLogged']
data_file_path:
description:
- Directory where the data files should be placed. Uses SQL Server's default if not supplied.
- Only used if database is being created.
type: str
required: false
log_file_path:
description:
- Directory where the log files should be placed. Uses SQL Server's default if not supplied.
- Only used if database is being created.
type: str
required: false
owner:
description:
- Database owner login.
type: str
required: false
maxdop:
description:
- MAXDOP value for the database.
required: false
type: int
secondary_maxdop:
description:
- MAXDOP value for the database when it is a non-primary replica in an availability group.
required: false
type: int
compatibility:
description:
- Compatibility mode for the database. Follows the format of C(Version90), C(Version100), and so on.
- String is validated by C(Set-DbaDbCompatibility).
required: false
type: str
rcsi:
description:
- Whether or not to enable Read Committed Snapshot Isolation.
required: false
type: bool
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create database
lowlydba.sqlserver.database:
sql_instance: sql-01.myco.io
database: LowlyDB
- name: Create database with customizations
lowlydba.sqlserver.database:
sql_instance: sql-01.myco.io
database: LowlyDB
owner: sa
maxdop: 2
recovery_model: Simple
'''
RETURN = r'''
data:
description: Modified output from the C(New-DbaDatabase), C(Set-DbaDatabase), or C(Remove-DbaDatabase) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,65 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
branch = @{type = 'str'; required = $false; choices = @('master', 'development') }
local_file = @{type = 'str'; required = $false }
database = @{type = 'str'; required = $true }
force = @{type = 'bool'; required = $false; default = $false }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$branch = $module.Params.branch
$localFile = $module.Params.local_file
$force = $module.Params.force
$checkMode = $module.Checkmode
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
$multiToolSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
Force = $force
}
if ($null -ne $localFile) {
$multiToolSplat.LocalFile = $localFile
}
if ($null -ne $branch) {
$multiToolSplat.Branch = $branch
}
try {
$output = Install-DbaMultiTool @multiToolSplat
$module.Result.changed = $true
# output is an array for each stored proc,
# rollup output into a single result
$errorProcs = $output | Where-Object Status -eq "Error"
if ($errorProcs) {
$output = $errorProcs[0] | Select-Object -ExcludeProperty Name
}
else {
$output = $output[0] | Select-Object -ExcludeProperty Name
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Installing DBA-MultiTool failed: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,63 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: dba_multitool
short_description: Install/update the DBA Multitool suite by John McCall
description:
- A wrapper for C(Install-DbaMultiTool) to fetch the latest version of the scripts, or install from a local cached version.
version_added: 0.7.0
options:
sql_instance:
description:
- The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher.
type: str
required: true
local_file:
description:
- Specifies the path to a local file to install DBA MultiTool from. This should be the zip file as distributed by the maintainers.
- If this option is not specified, the latest version will be downloaded and installed from https://github.com/LowlyDBA/dba-multitool/.
type: str
required: false
branch:
description:
- Specifies an alternate branch of the DBA MultiTool to install.
type: str
required: false
choices: ['master', 'development']
database:
description:
- Name of the target database.
type: str
required: true
force:
description:
- If this switch is enabled, the DBA MultiTool will be downloaded from the internet even if previously cached.
type: bool
default: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Install DBA MultiTool
lowlydba.sqlserver.dba_multitool:
sql_instance: test-server.my.company.com
database: dba_tools
'''
RETURN = r'''
data:
description: Modified output from the C(Install-DbaMultitool) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,80 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
branch = @{type = 'str'; required = $false; choices = @('main', 'dev') }
local_file = @{type = 'str'; required = $false }
only_script = @{type = 'str'; required = $false; default = 'Install-All-Scripts.sql'; choices = @('Install-All-Scripts.sql'
'Install-Core-Blitz-No-Query-Store.sql'
'Install-Core-Blitz-With-Query-Store.sql'
'sp_Blitz.sql'
'sp_BlitzFirst.sql'
'sp_BlitzIndex.sql'
'sp_BlitzCache.sql'
'sp_BlitzWho.sql'
'sp_BlitzQueryStore.sql'
'sp_BlitzAnalysis.sql'
'sp_BlitzBackups.sql'
'sp_BlitzInMemoryOLTP.sql'
'sp_BlitzLock.sql'
'sp_AllNightLog.sql'
'sp_AllNightLog_Setup.sql'
'sp_DatabaseRestore.sql'
'sp_ineachdb.sql'
'SqlServerVersions.sql'
'Uninstall.sql')
}
database = @{type = 'str'; required = $true }
force = @{type = 'bool'; required = $false; default = $false }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$branch = $module.Params.branch
$onlyScript = $module.Params.only_script
$localFile = $module.Params.local_file
$force = $module.Params.force
$checkMode = $module.Checkmode
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
$firstResponderKitSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
Force = $force
}
if ($localFile) {
$firstResponderKitSplat.Add("LocalFile", $localFile)
}
if ($branch) {
$firstResponderKitSplat.Add("Branch", $branch)
}
if ($onlyScript) {
$firstResponderKitSplat.Add("OnlyScript", $onlyScript)
}
try {
$output = Install-DbaFirstResponderKit @firstResponderKitSplat
$module.Result.changed = $true
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Installing First Responder Kit failed: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,84 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: first_responder_kit
short_description: Install/update the First Responder Kit scripts
description:
- A wrapper for C(Install-DbaFirstResponderKit) to fetch the latest version of the scripts, or install from a local cached version.
version_added: 0.10.0
options:
local_file:
description:
- Specifies the path to a local file to install FRK from. This should be the zip file as distributed by the maintainers.
- If this option is not specified, the latest version will be downloaded and installed Github.
type: str
required: false
only_script:
description:
- Specifies the name(s) of the script(s) to run for installation. Wildcards are permitted.
- This way only part of the First Responder Kit can be installed.
type: str
required: false
default: 'Install-All-Scripts.sql'
choices: ['Install-All-Scripts.sql',
'Install-Core-Blitz-No-Query-Store.sql',
'Install-Core-Blitz-With-Query-Store.sql',
'sp_Blitz.sql',
'sp_BlitzFirst.sql',
'sp_BlitzIndex.sql',
'sp_BlitzCache.sql',
'sp_BlitzWho.sql',
'sp_BlitzQueryStore.sql',
'sp_BlitzAnalysis.sql',
'sp_BlitzBackups.sql',
'sp_BlitzInMemoryOLTP.sql',
'sp_BlitzLock.sql',
'sp_AllNightLog.sql',
'sp_AllNightLog_Setup.sql',
'sp_DatabaseRestore.sql',
'sp_ineachdb.sql',
'SqlServerVersions.sql',
'Uninstall.sql']
branch:
description:
- Specifies an alternate branch of the First Responder Kit to install.
type: str
required: false
choices: ['main', 'dev']
database:
description:
- Name of the target database.
type: str
required: true
force:
description:
- If this switch is enabled, the FRK will be downloaded from the internet even if previously cached.
type: bool
default: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Install FRK
lowlydba.sqlserver.first_responder_kit:
sql_instance: test-server.my.company.com
database: dba_tools
'''
RETURN = r'''
data:
description: Modified output from the C(Install-DbaFirstResponderKit) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,71 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
# Get Csharp utility module
$spec = @{
supports_check_mode = $true
options = @{
username = @{type = 'str'; required = $false }
password = @{type = 'str'; required = $false; no_log = $true }
enabled = @{type = 'bool'; required = $false; default = $true }
force = @{type = 'bool'; required = $false; default = $false }
}
required_together = @(
, @('username', 'password')
)
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
if ($null -ne $Module.Params.username) {
[securestring]$secPassword = ConvertTo-SecureString $Module.Params.password -AsPlainText -Force
[pscredential]$credential = New-Object System.Management.Automation.PSCredential ($Module.Params.username, $secPassword)
}
$enabled = $module.Params.enabled
$force = $module.Params.force
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$server = Connect-DbaInstance -SqlInstance $sqlInstance -SqlCredential $sqlCredential
$existingHadr = $server | Get-DbaAgHadr -EnableException
$output = $existingHadr
if ($existingHadr.IsHadrEnabled -ne $enabled) {
$setHadr = @{
Credential = $credential
WhatIf = $checkMode
Force = $force
Confirm = $false
EnableException = $true
}
if ($enabled -eq $false) {
$output = $server | Disable-DbaAgHadr @setHadr
}
else {
$output = $server | Enable-DbaAgHadr @setHadr
}
if ($force -ne $true) {
$output | Add-Member -MemberType NoteProperty -Name "RestartRequired" -Value $true
}
$module.Result.changed = $true
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error configuring Hadr.", $_)
}

View File

@@ -0,0 +1,66 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: hadr
short_description: Enable or disable HADR
description:
- Enable or disable the High Availability Disaster Recovery (HADR) feature.
version_added: 0.4.0
options:
sql_instance:
description:
- The SQL Server instance to modify.
type: str
required: true
username:
description:
- Username for alternative credential to authenticate with Windows.
type: str
required: false
password:
description:
- Password for alternative credential to authenticate with Windows.
type: str
required: false
enabled:
description:
- Flag to enable or disable the feature.
type: bool
required: false
default: true
force:
description:
- Restart SQL Server and SQL Agent services automatically.
type: bool
required: false
default: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_win
'''
EXAMPLES = r'''
- name: Enable hadr with service restart
lowlydba.sqlserver.hadr:
sql_instance: sql-01.myco.io
enabled: true
force: true
'''
RETURN = r'''
data:
description:
- Output from the C(Enable-DbaAgHadr) or C(Disable-DbaAgHadr) function.
- RestartRequired returned if the setting requires a service restart to take effect.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,86 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
#Requires -Modules @{ ModuleName="dbops"; ModuleVersion="0.8.0" }
$spec = @{
supports_check_mode = $true
options = @{
database = @{type = 'str'; required = $true }
path = @{type = 'str'; required = $true }
deployment_method = @{type = 'str'; required = $false; default = 'NoTransaction'
choices = @('NoTransaction', 'SingleTransaction', 'TransactionPerScript')
}
schema_version_table = @{type = 'str'; required = $false }
no_log_version = @{type = 'bool'; required = $false; default = $false }
connection_timeout = @{type = 'int'; required = $false; default = 30 }
execution_timeout = @{type = 'int'; required = $false; default = 0 }
output_file = @{type = 'str'; required = $false }
create_database = @{type = 'bool'; required = $false; default = $false }
no_recurse = @{type = 'bool'; required = $false; default = $false }
match = @{type = 'str'; required = $false }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$schemaVersionTable = $module.Params.schema_version_table
$path = $module.Params.path
$outputFile = $module.Params.output_file
$match = $module.Params.match
$connectionTimeout = $module.Params.connection_timeout
$executionTimeout = $module.Params.execution_timeout
$createDatabase = $module.Params.create_database
$noRecurse = $module.Params.no_recurse
$noLogVersion = $module.Params.no_log_version
$checkMode = $module.Checkmode
$PSDefaultParameterValues = @{ "*:Confirm" = $false; "*:WhatIf" = $checkMode }
try {
$installSplat = @{
SqlInstance = $sqlInstance
Credential = $sqlCredential
Database = $database
Path = $path
ConnectionTimeout = $connectionTimeout
ExecutionTimeout = $executionTimeout
CreateDatabase = $createDatabase
NoRecurse = $noRecurse
Silent = $true
Type = "SqlServer"
}
if ($schemaVersionTable) {
$installSplat.Add("SchemaVersionTable", $schemaVersionTable)
}
if ($outputFile) {
$installSplat.Add("OutputFile", $outputFile)
}
if ($match) {
$installSplat.Add("Match", $match)
}
if ($noLogVersion) {
$installSplat.SchemaVersionTable = $null
}
$output = Install-DboScript @installSplat
if ($output.DeploymentLog[-1] -ne "No new scripts need to be executed - completing.") {
$module.Result.changed = $true
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
}
$module.ExitJson()
}
catch {
$module.FailJson("Failed migration script(s) execution: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,104 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: install_script
short_description: Runs migration scripts against a database
description:
- Uses the module C(DBOps) to run C(Dbo-InstallScript) against a target SQL Server database.
version_added: 0.11.0
options:
database:
description:
- Name of the target database.
required: true
type: str
path:
description:
- Directory where targeted sql scripts are stored.
type: str
required: true
schema_version_table:
description:
- A table that will hold the history of script execution. This table is used to choose what scripts are going to be
run during the deployment, preventing the scripts from being execured twice.
type: str
required: false
deployment_method:
description:
- C(SingleTransaction) - wrap all the deployment scripts into a single transaction and rollback whole deployment on error.
- C(TransactionPerScript) - wrap each script into a separate transaction; rollback single script deployment in case of error.
- C(NoTransaction) - deploy as is.
type: str
required: false
default: 'NoTransaction'
choices: ['NoTransaction', 'SingleTransaction', 'TransactionPerScript']
no_log_version:
description:
- If set, the deployment will not be tracked in the database. That will also mean that all the scripts
and all the builds from the package are going to be deployed regardless of any previous deployment history.
type: bool
default: false
required: false
connection_timeout:
description:
- Database server connection timeout in seconds. Only affects connection attempts. Does not affect execution timeout.
type: int
default: 30
required: false
execution_timeout:
description:
- Script execution timeout. The script will be aborted if the execution takes more than specified number of seconds.
type: int
default: 0
required: false
output_file:
description:
- Log output into specified file.
type: str
required: false
create_database:
description:
- Will create an empty database if missing.
type: bool
default: false
required: false
no_recurse:
description:
- Only process the first level of the target path.
type: bool
required: false
default: false
match:
description:
- Runs a regex verification against provided file names using the provided string.
type: str
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
- L(dbops,https://github.com/dataplat/dbops) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Migrate a database
lowlydba.sqlserver.install_script:
sql_instance: test-server.my.company.com
database: AdventureWorks
path: migrations
'''
RETURN = r'''
data:
description: Modified output from the C(Install-DboScript) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,57 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
# Get Csharp utility module
$spec = @{
supports_check_mode = $true
options = @{}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$module.Result.changed = $false
# Fetch instance information
try {
$getSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
EnableException = $true
}
$output = Get-DbaConnection @getSplat | Select-Object -Property "ComputerName", "SqlInstance", "InstanceName" -First 1
if ($null -ne $output) {
# Add additional fields
$extraProperties = @(
"BuildNumber"
"Language"
"VersionMajor"
"VersionMinor"
"VersionString"
"Collation"
"ProductLevel"
"IsClustered"
"LoginMode"
)
foreach ($prop in $extraProperties) {
$value = (Get-DbaInstanceProperty @getSplat -InstanceProperty $prop).Value
$output | Add-Member -MemberType NoteProperty -Name $prop -Value $value
}
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error fetching instance information: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,34 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: instance_info
short_description: Returns basic information for a SQL Server instance
description:
- Returns basic information for a SQL Server instance.
version_added: 0.2.0
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode_read_only
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Get basic info for an instance
lowlydba.sqlserver.instance_info:
sql_instance: sql-01.myco.io
'''
RETURN = r'''
data:
description: Instance level properties of the SQL Server instance.
returned: always
type: dict
'''

View File

@@ -0,0 +1,144 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
login = @{type = 'str'; required = $true }
password = @{type = 'str'; required = $false; no_log = $true }
enabled = @{type = 'bool'; required = $false; default = $true }
default_database = @{type = 'str'; required = $false }
language = @{type = 'str'; required = $false }
password_must_change = @{type = 'bool'; required = $false }
password_policy_enforced = @{type = 'bool'; required = $false }
password_expiration_enabled = @{type = 'bool'; required = $false }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$login = $module.Params.login
if ($null -ne $module.Params.password) {
$secPassword = ConvertTo-SecureString -String $module.Params.password -AsPlainText -Force
}
$enabled = $module.Params.enabled
$defaultDatabase = $module.Params.default_database
$language = $module.Params.language
[nullable[bool]]$passwordMustChange = $module.Params.password_must_change
[nullable[bool]]$passwordExpirationEnabled = $module.Params.password_expiration_enabled
[nullable[bool]]$passwordPolicyEnforced = $module.Params.password_policy_enforced
$state = $module.Params.state
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$getLoginSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Login = $login
ExcludeSystemLogin = $true
EnableException = $true
}
$existingLogin = Get-DbaLogin @getLoginSplat
if ($state -eq "absent") {
if ($null -ne $existingLogin) {
$output = $existingLogin | Remove-DbaLogin -WhatIf:$checkMode -EnableException -Force -Confirm:$false
$module.Result.changed = $true
}
}
elseif ($state -eq "present") {
$setLoginSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Login = $login
WhatIf = $checkMode
EnableException = $true
Confirm = $false
}
if ($null -ne $defaultDatabase) {
$setLoginSplat.add("DefaultDatabase", $defaultDatabase)
}
if ($null -ne $passwordExpirationEnabled) {
if ($existingLogin.PasswordExpirationEnabled -ne $passwordExpirationEnabled) {
$changed = $true
}
if ($passwordExpirationEnabled -eq $true) {
$setLoginSplat.add("PasswordExpirationEnabled", $true)
}
}
if ($null -ne $passwordPolicyEnforced) {
if ($existingLogin.PasswordPolicyEnforced -ne $passwordPolicyEnforced) {
$changed = $true
}
if ($passwordPolicyEnforced -eq $true) {
$setLoginSplat.add("PasswordPolicyEnforced", $true)
}
}
if ($true -eq $passwordMustChange) {
if ($existingLogin.PasswordMustChange -ne $passwordMustChange) {
$changed = $true
}
if ($passwordMustChange -eq $true) {
$setLoginSplat.add("PasswordMustChange", $true)
}
}
if ($null -ne $secPassword) {
$setLoginSplat.add("SecurePassword", $secPassword)
}
# Login already exists
if ($null -ne $existingLogin) {
if ($enabled -eq $false) {
$disabled = $true
$setLoginSplat.add("Disable", $true)
}
else {
$disabled = $false
$setLoginSplat.add("Enable", $true)
}
# Login needs to be modified
if (($changed -eq $true) -or ($disabled -ne $existingLogin.IsDisabled) -or ($secPassword)) {
$output = Set-DbaLogin @setLoginSplat
$module.result.changed = $true
}
}
# New login
else {
if ($null -ne $language) {
$setLoginSplat.add("Language", $language)
}
if ($enabled -eq $false) {
$setLoginSplat.add("Disabled", $true)
}
$output = New-DbaLogin @setLoginSplat
$module.result.changed = $true
}
# If not in check mode, add extra fields we can change to default display set
if ($null -ne $output) {
$output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("DefaultDatabase")
$output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("Language")
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Configuring login failed: $($_.Exception.Message) ; $setLoginSplat", $_)
}

View File

@@ -0,0 +1,89 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: login
short_description: Configures a login for the target SQL Server instance
description:
- Creates, modifies, or removes a Windows or SQL Authentication login on a SQL Server instance.
version_added: 0.1.0
options:
login:
description:
- Name of the login to configure.
type: str
required: true
password:
description:
- Password for the login, if SQL Authentication login.
type: str
required: false
enabled:
description:
- Whether the login is enabled or disabled.
type: bool
required: false
default: true
version_added: '0.4.0'
default_database:
description:
- Default database for the login.
type: str
required: false
language:
description:
- Default language for the login. Only used when creating a new login, not when modifying an existing one.
type: str
required: false
password_must_change:
description:
- Enforces user must change password at next login.
- When specified will enforce I(password_expiration_enabled) and I(password_policy_enforced) as they are required.
type: bool
required: false
password_policy_enforced:
description:
- Enforces password complexity policy.
type: bool
required: false
password_expiration_enabled:
description:
- Enforces password expiration policy. Requires I(password_policy_enforced=true).
type: bool
required: false
author: "John McCall (@lowlydba)"
notes:
- Module will always return changed if a password is supplied.
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Create a login
lowlydba.sqlserver.login:
sql_instance: sql-01.myco.io
login: TheIntern
password: ReallyComplexStuff12345!
- name: Disable a login
lowlydba.sqlserver.login:
sql_instance: sql-01.myco.io
login: TheIntern
enabled: false
'''
RETURN = r'''
data:
description: Output from the C(New-DbaLogin), C(Set-DbaLogin), or C(Remove-DbaLogin) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,105 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
backup_location = @{type = 'str'; required = $false }
cleanup_time = @{type = 'int'; required = $false; default = 0 }
output_file_dir = @{type = 'str'; required = $false }
replace_existing = @{type = 'bool'; required = $false; }
log_to_table = @{type = 'bool'; required = $false; default = $false }
solution = @{type = 'str'; required = $false; choices = @('All', 'Backup', 'IntegrityCheck', 'IndexOptimize'); default = 'All' }
install_jobs = @{type = 'bool'; required = $false; default = $false }
local_file = @{type = 'str'; required = $false }
database = @{type = 'str'; required = $true }
force = @{type = 'bool'; required = $false; default = $false }
install_parallel = @{type = 'bool'; required = $false; default = $false }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$backupLocation = $module.Params.backup_location
$outputFileDirectory = $module.Params.output_file_dir
$cleanupTime = $module.Params.cleanup_time
$replaceExisting = $module.Params.replace_existing
$solution = $module.Params.solution
$installJobs = $module.Params.install_jobs
$installParallel = $module.Params.install_parallel
$logToTable = $module.Params.log_to_table
$localFile = $module.Params.local_file
$force = $module.Params.force
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$maintenanceSolutionSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
LogToTable = $logToTable
Solution = $solution
InstallJobs = $installJobs
InstallParallel = $installParallel
WhatIf = $checkMode
Force = $force
Confirm = $false
EnableException = $true
}
if ($null -ne $localFile) {
$maintenanceSolutionSplat.LocalFile = $localFile
}
if ($null -ne $backupLocation) {
$maintenanceSolutionSplat.BackupLocation = $backupLocation
}
if ($null -ne $outputFileDirectory) {
$maintenanceSolutionSplat.OutputFileDirectory = $outputFileDirectory
}
if ($installJobs -eq $true -and $null -ne $cleanupTime) {
$maintenanceSolutionSplat.CleanupTime = $cleanupTime
}
# Only pass if true, otherwise removes warning that is used to track changed=$false
if ($replaceExisting -eq $true) {
$maintenanceSolutionSplat.ReplaceExisting = $replaceExisting
}
try {
$output = Install-DbaMaintenanceSolution @maintenanceSolutionSplat
$module.Result.changed = $true
}
catch {
$errMessage = $_.Exception.Message
if ($errMessage -like "*Maintenance Solution already exists*") {
$server = Connect-DbaInstance -SqlInstance $sqlInstance -SqlCredential $sqlCredential
$output = [PSCustomObject]@{
ComputerName = $server.ComputerName
InstanceName = $server.ServiceName
SqlInstance = $server.DomainInstanceName
Results = "Success"
}
}
else {
Write-Error -Message $errMessage
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Installing Maintenance Solution failed.", $_)
}

View File

@@ -0,0 +1,101 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: maintenance_solution
short_description: Install/update Maintenance Solution by Ola Hallengren
description:
- A wrapper for C(Install-DbaMaintenanceSolution) to fetch the latest version of the Ola Hallengren's Maintenance Solution,
or install from a local cached version.
version_added: 0.1.0
options:
backup_location:
description:
- Location of the backup root directory. If this is not supplied, the default backup directory will be used.
type: str
required: false
cleanup_time:
description:
- Time in hours, after which backup files are deleted.
type: int
required: false
default: 0
output_file_dir:
description:
- Specify the output file directory where the Maintenance Solution will write to.
type: str
required: false
replace_existing:
description:
- If this switch is enabled, objects already present in the target database will be dropped and recreated.
type: bool
required: false
log_to_table:
description:
- If this switch is enabled, the Maintenance Solution will be configured to log commands to a table.
type: bool
required: false
default: false
solution:
description:
- Specifies which portion of the Maintenance Solution to install.
type: str
required: false
default: 'All'
choices: ['All', 'Backup', 'IntegrityCheck', 'IndexOptimize']
install_jobs:
description:
- If this switch is enabled, the corresponding SQL Agent Jobs will be created.
type: bool
required: false
default: false
install_parallel:
description:
- If this switch is enabled, the C(Queue) and C(QueueDatabase) tables are created, for use when C(@DatabasesInParallel = 'Y') are set in the jobs.
type: bool
required: false
default: false
local_file:
description:
- Specifies the path to a local file to install Ola's solution from. This should be the zip file as distributed by the maintainers.
- If this option is not specified, the latest version will be downloaded and installed
from the L(Maintenance Solution Github,https://github.com/olahallengren/sql-server-maintenance-solution).
type: str
required: false
database:
description:
- Name of the target database.
type: str
required: true
force:
description:
- If this switch is enabled, the Maintenance Solution will be downloaded from the internet even if previously cached.
type: bool
default: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Install/Update Maintenance Solution
lowlydba.sqlserver.multitool:
sql_instance: sql-01.myco.io
database: main
replace_existing: true
'''
RETURN = r'''
data:
description: Output from the C(Install-MaintenanceSolution) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,50 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
# Get Csharp utility module
$spec = @{
supports_check_mode = $true
options = @{
max = @{type = "int"; required = $false; default = 0 }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$max = $module.Params.max
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
# Set max memory for SQL Instance
try {
# Set max memory
$setMemorySplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Max = $max
}
$output = Set-DbaMaxMemory @setMemorySplat
if ($output.PreviousMaxValue -ne $output.MaxValue -or $checkMode) {
$module.Result.changed = $true
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Error setting max memory.", $_)
}

View File

@@ -0,0 +1,46 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: memory
short_description: Sets the maximum memory for a SQL Server instance
description:
- Sets the maximum memory for a SQL Server instance.
version_added: 0.1.0
options:
max:
description:
- The maximum memory in MB that the SQL Server instance can utilize. C(0) will automatically calculate the ideal value.
type: int
required: false
default: 0
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Automatically configure SQL max memory
lowlydba.sqlserver.memory:
sql_instance: sql-01.myco.io
- name: Manually configure SQL max memory
lowlydba.sqlserver.memory:
sql_instance: sql-01.myco.io
max: 10240
'''
RETURN = r'''
data:
description: Output from the C(Set-DbaMaxMemory) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,51 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
# Get Csharp utility module
$spec = @{
supports_check_mode = $true
options = @{
database = @{type = 'str'; required = $true }
nonquery = @{type = 'str'; required = $true }
query_timeout = @{type = 'int'; required = $false; default = 60 }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$nonquery = $module.Params.nonquery
$queryTimeout = $module.Params.query_timeout
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$invokeQuerySplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Database = $database
Query = $nonquery
QueryTimeout = $queryTimeout
EnableException = $true
}
if ($checkMode) {
$invokeQuerySplat.Add("NoExec", $true)
}
$null = Invoke-DbaQuery @invokeQuerySplat
$module.Result.changed = $true
$module.ExitJson()
}
catch {
$module.FailJson("Executing nonquery failed.", $_)
}

View File

@@ -0,0 +1,48 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: nonquery
short_description: Executes a generic nonquery
description:
- Execute a nonquery against a database. Does not return a resultset. Ideal for ad-hoc configurations or DML queries.
version_added: 0.1.0
options:
database:
description:
- Name of the database to execute the nonquery in.
type: str
required: true
nonquery:
description:
- The nonquery to be executed.
type: str
required: true
query_timeout:
description:
- Number of seconds to wait before timing out the nonquery execution.
type: int
required: false
default: 60
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Update a table value
lowlydba.sqlserver.nonquery:
sql_instance: sql-01-myco.io
database: userdb
nonquery: "UPDATE dbo.User set IsActive = 1;"
'''
RETURN = r''' # '''

View File

@@ -0,0 +1,69 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
enabled = @{type = 'bool'; required = $false; default = $true }
classifier_function = @{type = 'str'; required = $false }
}
}
# Get Csharp utility module
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$enabled = $module.Params.enabled
$classifierFunction = $module.Params.classifier_function
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
try {
$rg = Get-DbaResourceGovernor -SqlInstance $sqlInstance -SqlCredential $sqlCredential
$rgClassifierFunction = $rg.ClassifierFunction
if ($rg.Enabled -ne $enabled) {
$change = $true
}
if ($classifierFunction -ne "NULL" -and $rgClassifierFunction -ne $classifierFunction) {
$change = $true
}
if ($classifierFunction -eq "NULL" -and $null -ne $rgClassifierFunction) {
$change = $true
}
if ($change) {
$rgSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
ClassifierFunction = $classifierFunction
}
if ($enabled) {
$rgSplat.Add("Enabled", $true)
}
else {
$rgSplat.Add("Disabled", $true)
}
$output = Set-DbaResourceGovernor @rgSplat
$module.Result.changed = $true
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Setting resource governor failed.", $_)
}

View File

@@ -0,0 +1,47 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: resource_governor
short_description: Configures the resource governor on a SQL Server instance
description:
- Enables or disables and optionally sets the classifier function for the resource governor feature.
version_added: 0.1.0
options:
enabled:
description:
- Whether to enable or disable resource governor.
type: bool
required: false
default: true
classifier_function:
description:
- The name of the classifier function that resource governor will use. To clear the function, use the string C(NULL).
type: str
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Enable resource governor
lowlydba.sqlserver.resource_governor:
sql_instance: sql-01.myco.io
enabled: true
'''
RETURN = r'''
data:
description: Output from the C(Set-DbaResourceGovernor) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,170 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
database = @{type = 'str'; required = $false }
path = @{type = 'str'; required = $true }
destination_data_directory = @{type = 'str'; required = $false }
destination_log_directory = @{type = 'str'; required = $false }
destination_filestream_directory = @{type = 'str'; required = $false }
restore_time = @{type = 'str'; required = $false }
with_replace = @{type = 'bool'; required = $false; default = $false }
keep_replication = @{type = 'bool'; required = $false; default = $false }
xp_dirtree = @{type = 'bool'; required = $false }
no_xp_dir_recurse = @{type = 'bool'; required = $false; default = $false }
verify_only = @{type = 'bool'; required = $false; default = $false }
maintenance_solution_backup = @{type = 'bool'; required = $false; default = $false }
ignore_log_backup = @{type = 'bool'; required = $false; default = $false }
ignore_diff_backup = @{type = 'bool'; required = $false; default = $false }
use_destination_default_directories = @{type = 'bool'; required = $false }
reuse_source_folder_structure = @{type = 'bool'; required = $false }
destination_file_prefix = @{type = 'str'; required = $false }
restored_database_name_prefix = @{type = 'str'; required = $false }
directory_recurse = @{type = 'bool'; required = $false; default = $false }
standby_directory = @{type = 'str'; required = $false }
replace_db_name_in_file = @{type = 'bool'; required = $false }
destination_file_suffix = @{type = 'str'; required = $false }
keep_cdc = @{type = 'bool'; required = $false }
stop_before = @{type = 'bool'; required = $false; default = $false }
stop_mark = @{type = 'str'; required = $false }
stop_after_date = @{type = 'str'; required = $false }
no_recovery = @{type = 'bool'; required = $false; default = $false }
max_transfer_size = @{type = 'int'; required = $false; default = 0 }
block_size = @{type = 'str'; required = $false; choices = @('0.5kb', '1kb', '2kb', '4kb', '8kb', '16kb', '32kb', '64kb') }
buffer_count = @{type = 'int'; required = $false; default = 0 }
azure_credential = @{type = 'str'; required = $false }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$path = $module.Params.path
$destinationDataDirectory = $module.Params.destination_data_directory
$destinationLogDirectory = $module.Params.destination_log_directory
$destinationFilestreamDirectory = $module.Params.destination_filestream_directory
$restoreTime = $module.Params.restore_time
$withReplace = $module.Params.with_replace
$keepReplication = $module.Params.keep_replication
$xpDirTree = $module.Params.xp_dirtree
$noXpDirRecurse = $module.Params.no_xp_dir_recurse
$verifyOnly = $module.Params.verify_only
$maintenanceSolutionBackup = $module.Params.maintenance_solution_backup
$ignoreLogBackup = $module.Params.ignore_log_backup
$ignoreDiffBackup = $module.Params.ignore_diff_backup
$useDestinationDefaultDirectories = $module.Params.use_destination_default_directories
$reuseSourceFolderStructure = $module.Params.reuse_source_folder_structure
$destinationFilePrefix = $module.Params.destination_file_prefix
$restoredDatabaseNamePrefix = $module.Params.restored_database_name_prefix
$directoryRecurse = $module.Params.directory_recurse
$standbyDirectory = $module.Params.standby_directory
$replaceDbNameInFile = $module.Params.replace_db_name_in_file
$destinationFileSuffix = $module.Params.destination_file_suffix
$keepCDC = $module.Params.keep_cdc
$stopBefore = $module.Params.stop_before
$stopMark = $module.Params.stop_mark
$stopAfterDate = $module.Params.stop_after_date
$noRecovery = $module.Params.no_recovery
$maxTransferSize = $module.Params.max_transfer_size
$blockSize = $module.Params.block_size
$bufferCount = $module.Params.buffer_count
$azureCredential = $modules.Param.azure_credential
$checkMode = $module.CheckMode
$module.Result.changed = $false
$PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
try {
$restoreSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Path = $path
WithReplace = $withReplace
KeepReplication = $keepReplication
NoXpDirRecurse = $noXpDirRecurse
VerifyOnly = $verifyOnly
MaintenanceSolutionBackup = $maintenanceSolutionBackup
IgnoreLogBackup = $ignoreLogBackup
IgnoreDiffBackup = $ignoreDiffBackup
DirectoryRecurse = $directoryRecurse
StopBefore = $stopBefore
NoRecovery = $noRecovery
MaxTransferSize = $maxTransferSize
BufferCount = $bufferCount
}
if ($null -ne $database) {
$restoreSplat.Add("DatabaseName", $database)
}
if ($null -ne $destinationDataDirectory) {
$restoreSplat.Add("DestinationDataDirectory", $destinationDataDirectory)
}
if ($null -ne $destinationLogDirectory) {
$restoreSplat.Add("DestinationLogDirectory", $destinationLogDirectory)
}
if ($null -ne $destinationFilestreamDirectory) {
$restoreSplat.Add("DestinationFilestreamDirectory", $destinationFilestreamDirectory)
}
if ($null -ne $restoreTime) {
$restoreSplat.Add("RestoreTime", $restoreTime)
}
if ($null -ne $destinationFilePrefix) {
$restoreSplat.Add("DestinationFilePrefix", $destinationFilePrefix)
}
if ($null -ne $restoredDatabaseNamePrefix) {
$restoreSplat.Add("RestoredDatabaseNamePrefix", $restoredDatabaseNamePrefix)
}
if ($null -ne $standbyDirectory) {
$restoreSplat.Add("StandbyDirectory", $standbyDirectory)
}
if ($null -ne $destinationFileSuffix) {
$restoreSplat.Add("DestinationFileSuffix", $destinationFileSuffix)
}
if ($null -ne $stopAfterDate) {
$restoreSplat.Add("StopAfterDate", $stopAfterDate)
}
if ($null -ne $stopMark) {
$restoreSplat.Add("StopMark", $stopMark)
}
if ($null -ne $blockSize) {
$restoreSplat.Add("BlockSize", ($blockSize / 1))
}
if ($null -ne $azureCredential) {
$restoreSplat.Add("AzureCredential", $azureCredential)
}
if ($null -ne $xpDirTree) {
$restoreSplat.Add("xpDirTree", $xpDirTree)
}
if ($null -ne $reuseSourceFolderStructure) {
$restoreSplat.Add("reuseSourceFolderStructure", $reuseSourceFolderStructure)
}
if ($null -ne $replaceDbNameInFile) {
$restoreSplat.Add("replaceDbNameInFile", $replaceDbNameInFile)
}
if ($null -ne $useDestinationDefaultDirectories) {
$restoreSplat.Add("useDestinationDefaultDirectories", $useDestinationDefaultDirectories)
}
if ($null -ne $keepCDC) {
$restoreSplat.Add("KeepCDC", $keepCDC)
}
$output = Restore-DbaDatabase @restoreSplat
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
$module.Result.changed = $true
}
$module.ExitJson()
}
catch {
$module.FailJson("Error restoring database: $($_.Exception.Message).", $_)
}

View File

@@ -0,0 +1,230 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: restore
short_description: Performs a restore operation
description:
- Performs a database restore operation.
version_added: 0.9.0
options:
database:
description:
- The database to process.
type: str
required: false
path:
description:
- Path to SQL Server backup files.
- Paths passed in as strings will be scanned using the desired method, default is a recursive folder scan.
- Accepts multiple paths separated by C(,).
type: str
required: true
destination_data_directory:
description:
- Path to restore the SQL Server backups to on the target instance.
- If only this option is specified, then all database files (data and log) will be restored to this location
type: str
required: false
destination_log_directory:
description:
- Path to restore the database log files to.
- This option can only be specified alongside I(destination_data_directory).
type: str
required: false
destination_filestream_directory:
description:
- Path to restore FileStream data to.
- This option can only be specified alongside I(destination_data_directory).
type: str
required: false
restore_time:
description:
- Specify a datetime string C(HH:MM:SS MM/DD/YYYY) to which you want the database restored to.
- Default is to the latest point available in the specified backups.
type: str
required: false
with_replace:
description:
- Indicates if the restore is allowed to replace an existing database.
type: bool
required: false
default: false
keep_replication:
description:
- Indicates whether replication configuration should be restored as part of the database restore operation.
type: bool
required: false
default: false
xp_dirtree:
description:
- Switch that indicated file scanning should be performed by the SQL Server instance using C(xp_dirtree).
- This will scan recursively from the passed in path.
- You must have sysadmin role membership on the instance for this to work.
type: bool
required: false
no_xp_dir_recurse:
description:
- If specified, prevents the C(XpDirTree) process from recursing (its default behaviour).
type: bool
required: false
default: false
verify_only:
description:
- Indicates the restore should be verified only.
type: bool
required: false
default: false
maintenance_solution_backup:
description:
- Switch to indicate the backup files are in a folder structure as created by Ola Hallengreen's maintenance scripts.
- This allows for faster file parsing.
type: bool
required: false
default: false
ignore_log_backup:
description:
- Indicates to skip restoring any log backups.
type: bool
required: false
default: false
ignore_diff_backup:
description:
- Indicates to skip restoring any differential backups.
type: bool
required: false
default: false
use_destination_default_directories:
description:
- Switch that tells the restore to use the default Data and Log locations on the target server.
- If they don't exist, the function will try to create them.
type: bool
required: false
reuse_source_folder_structure:
description:
- By default, databases will be migrated to the destination Sql Server's default data and log directories.
- You can override this by using C(reuse_source_folder_structure).
type: bool
required: false
destination_file_prefix:
description:
- This value will be prefixed to B(all) restored files (log and data).
type: str
required: false
restored_database_name_prefix:
description:
- A string which will be prefixed to the start of the restore Database's name.
type: str
required: false
directory_recurse:
description:
- If specified the specified directory will be recursed into (overriding the default behaviour).
type: bool
required: false
default: false
standby_directory:
description:
- If a directory is specified the database(s) will be restored into a standby state,
with the standby file placed into this directory (which must exist, and be writable by the target Sql Server instance).
type: str
required: false
replace_db_name_in_file:
description:
- If switch set any occurrence of the original database's name in a data or log file
will be replace with the name specified in the I(database_name) option.
type: bool
required: false
destination_file_suffix:
description:
- This value will be suffixed to B(all) restored files (log and data).
type: str
required: false
keep_cdc:
description:
- Indicates whether CDC information should be restored as part of the database.
type: bool
required: false
stop_before:
description:
- Switch to indicate the restore should stop before I(stop_mark) occurs, default is to stop when mark is created.
type: bool
required: false
default: false
stop_mark:
description:
- Marked point in the transaction log to stop the restore at.
type: str
required: false
stop_after_date:
description:
- By default the restore will stop at the first occurence of I(stop_mark) found in the chain,
passing a datetime string C(HH:MM:SS MM/DD/YYYY) will cause it to stop the first I(stop_mark) after that datetime.
type: str
required: false
no_recovery:
description:
- Indicates if the databases should be recovered after last restore.
type: bool
required: false
default: false
max_transfer_size:
description:
- Sets the size of the unit of transfer. Values must be a multiple of 64kb.
type: int
required: false
default: 0
block_size:
description:
- Specifies block size to use.
type: str
required: false
choices: ['0.5kb','1kb','2kb','4kb','8kb','16kb','32kb','64kb']
buffer_count:
description:
- Number of I/O buffers to use.
type: int
required: false
default: 0
azure_credential:
description:
- The name of the SQL Server credential to be used if restoring from an Azure hosted backup using Storage Access Keys.
type: str
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Restore a Database
lowlydba.sqlserver.restore:
sql_instance: sql-01.myco.io
database: LowlyDB
- name: Restore a Database and allow future T-Log restores
lowlydba.sqlserver.restore:
sql_instance: sql-01.myco.io
database: LowlyDB1
no_recovery: true
- name: Verify backup files, no restore
lowlydba.sqlserver.restore:
sql_instance: sql-01.myco.io
database: LowlyDB2
verify_only: true
'''
RETURN = r'''
data:
description: Modified output from the C(Restore-DbaDatabase) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,118 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
resource_pool = @{type = 'str'; required = $true }
type = @{type = 'str'; required = $false; default = 'Internal'; choices = @('Internal', 'External') }
max_cpu_perc = @{type = 'int'; required = $false; }
min_cpu_perc = @{type = 'int'; required = $false; }
cap_cpu_perc = @{type = 'int'; required = $false; }
max_mem_perc = @{type = 'int'; required = $false; }
min_mem_perc = @{type = 'int'; required = $false; }
min_iops_per_vol = @{type = 'int'; required = $false; }
max_iops_per_vol = @{type = 'int'; required = $false; }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$state = $module.Params.state
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$options = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
ResourcePool = $module.Params.resource_pool
Type = $module.Params.type
MaximumCpuPercentage = $module.Params.max_cpu_perc
MinimumCpuPercentage = $module.Params.min_cpu_perc
CapCpuPercentage = $module.Params.cap_cpu_perc
MaximumMemoryPercentage = $module.params.max_mem_perc
MinimumMemoryPercentage = $module.Params.min_mem_perc
MinimumIOPSPerVolume = $module.params.min_iops_per_vol
MaximumIOPSPerVolume = $module.params.max_iops_per_vol
}
$checkMode = $module.CheckMode
$module.Result.changed = $false
[System.Collections.ArrayList]$compareProperty = @(
'MaximumCpuPercentage',
'MinimumCpuPercentage',
'CapCpuPercentage',
'MinimumMemoryPercentage',
'MaximumMemoryPercentage',
'MinimumIOPSPerVolume',
'MaximumIOPSPerVolume'
)
$optionsToRemove = @()
foreach ($item in $options.GetEnumerator() ) {
if ($null -eq $item.Value) {
$optionsToRemove += $item.Name
}
}
foreach ($item in $optionsToRemove) {
$options.Remove($item)
$compareProperty.Remove($item)
}
try {
$getPoolParams = @{
SqlInstance = $options.SqlInstance
SqlCredential = $options.SqlCredential
Type = $options.Type
EnableException = $true
}
$existingResourcePool = Get-DbaRgResourcePool @getPoolParams | Where-Object Name -eq $options.ResourcePool
if ($state -eq "absent") {
if ($null -ne $existingResourcePool) {
$removePoolParams = @{
SqlInstance = $options.SqlInstance
SqlCredential = $options.SqlCredential
Type = $options.Type
ResourcePool = $options.ResourcePool
WhatIf = $checkMode
EnableException = $true
Confirm = $false
}
$output = Remove-DbaRgResourcePool @removePoolParams
$module.Result.changed = $true
}
}
elseif ($state -eq "present") {
$options.Add("WhatIf", $checkMode)
if ($null -ne $existingResourcePool) {
# Check for value parity
$diff = Compare-Object -ReferenceObject $options -DifferenceObject $existingResourcePool -Property $compareProperty
if ($null -ne $diff) {
# Set to new values
$output = Set-DbaRgResourcePool @options -EnableException
$module.Result.changed = $true
}
}
else {
# Create a resource pool
$output = New-DbaRgResourcePool @options -EnableException
$module.Result.changed = $true
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Configuring resource pool failed: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,90 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: rg_resource_pool
short_description: Configures a resource pool for use by the Resource Governor
description:
- Creates or modifies a resource pool to be used by the Resource Governor. Default values are handled by the Powershell functions themselves.
version_added: 0.1.0
options:
resource_pool:
description:
- Name of the target resource pool.
type: str
required: true
type:
description:
- Specify the type of resource pool.
type: str
required: false
default: 'Internal'
choices: ['Internal', 'External']
max_cpu_perc:
description:
- Maximum CPU Percentage able to be used by queries in this resource pool.
type: int
required: false
min_cpu_perc:
description:
- Minimum CPU Percentage able to be used by queries in this resource pool.
type: int
required: false
cap_cpu_perc:
description:
- Cap CPU Percentage able to be used by queries in this resource pool.
type: int
required: false
max_mem_perc:
description:
- Maximum Memory Percentage able to be used by queries in this resource pool.
type: int
required: false
min_mem_perc:
description:
- Minimum Memory Percentage able to be used by queries in this resource pool.
type: int
required: false
max_iops_per_vol:
description:
- Maximum IOPS/volume able to be used by queries in this resource pool.
type: int
required: false
min_iops_per_vol:
description:
- Minimum IOPS/volume able to be used by queries in this resource pool.
type: int
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Enable resource governor
lowlydba.sqlserver.resource_governor:
sql_instance: sql-01.myco.io
enabled: true
- name: Create rg resource pool
lowlydba.sqlserver.rg_resource_pool:
sql_instance: sql-01.myco.io
resource_pool: "rpLittle"
max_cpu_perc: 5
'''
RETURN = r'''
data:
description: Output from the C(Set-DbaRgResourcePool), C(New-DbaRgResourcePool), or C(Remove-DbaRgResourcePool) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,112 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
workload_group = @{type = 'str'; required = $true; }
resource_pool = @{type = 'str'; required = $true; }
resource_pool_type = @{type = 'str'; required = $false; default = 'Internal'; choices = @('Internal', 'External') }
group_max_requests = @{type = 'int'; required = $false; }
importance = @{type = 'str'; required = $false; choices = @('Low', 'Medium', 'High') }
max_dop = @{type = 'int'; required = $false; }
request_max_cpu_time = @{type = 'int'; required = $false; }
request_max_mem_grant_perc = @{type = 'int'; required = $false; }
request_mem_grant_timeout_sec = @{type = 'int'; required = $false; }
state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
}
}
# Get Csharp utility module
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$options = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
WorkloadGroup = $module.Params.workload_group
ResourcePool = $module.Params.resource_pool
ResourcePoolType = $module.Params.resource_pool_type
GroupMaximumRequests = $module.Params.group_max_requests
Importance = $module.Params.importance
MaximumDegreeOfParallelism = $module.Params.max_dop
RequestMaximumCpuTimeInSeconds = $module.Params.request_max_cpu_time
RequestMaximumMemoryGrantPercentage = $module.Params.request_max_mem_grant_perc
RequestMemoryGrantTimeoutInSeconds = $module.Params.request_mem_grant_timeout_sec
}
$state = $module.Params.state
$module.Result.changed = $false
$checkMode = $module.CheckMode
[System.Collections.ArrayList]$compareProperty = @(
'GroupMaximumRequests',
'Importance',
'MaximumDegreeOfParallelism',
'RequestMaximumCpuTimeInSeconds',
'RequestMemoryGrantTimeoutInSeconds',
'RequestMaximumMemoryGrantPercentage'
)
# Remove unsupplied params - the dbatools functions handle default value checks
$optionsToRemove = @()
foreach ($item in $options.GetEnumerator() ) {
if ($null -eq $item.Value) {
$optionsToRemove += $item.Name
}
}
foreach ($item in $optionsToRemove) {
$options.Remove($item)
$compareProperty.Remove($item)
}
try {
$getResourcePoolSplat = @{
SqlInstance = $options.SqlInstance
SqlCredential = $options.SqlCredential
Type = $options.ResourcePoolType
}
$existingResourcePool = Get-DbaRgResourcePool @getResourcePoolSplat | Where-Object Name -eq $options.ResourcePool
if ($null -eq $existingResourcePool) {
$module.FailJson("Failed to lookup parent resource pool '$($options.ResourcePool)'.", $_)
}
$existingWorkloadGroup = $existingResourcePool.WorkloadGroups | Where-Object Name -eq $options.WorkloadGroup
if ($state -eq "absent") {
if ($null -ne $existingResourcePool) {
$output = $existingWorkloadGroup | Remove-DbaRgWorkloadGroup -WhatIf:$checkMode -EnableException
$module.Result.changed = $true
}
}
elseif ($state -eq "present") {
if ($null -ne $existingWorkloadGroup) {
# Check for value parity
$diff = Compare-Object -ReferenceObject $existingWorkloadGroup -DifferenceObject $options -Property $compareProperty
# Set to new values
if ($null -ne $diff) {
$output = Set-DbaRgWorkloadGroup @options -WhatIf:$checkMode -EnableException
$module.Result.changed = $true
}
}
else {
# Create a new workload group
$output = New-DbaRgWorkloadGroup @options -WhatIf:$checkMode -EnableException
$module.Result.changed = $true
}
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Failed to configure workload group: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,100 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: rg_workload_group
short_description: Configures a workload group for use by the Resource Governor
description:
- Creates or modifies a workload group to be used by the Resource Governor. Default values are handled by the Powershell functions themselves.
version_added: 0.1.0
options:
workload_group:
description:
- Name of the target workload group.
type: str
required: true
resource_pool:
description:
- Name of the resource pool for the workload group.
type: str
required: true
resource_pool_type:
description:
- Specify the type of resource pool.
type: str
required: false
default: 'Internal'
choices: ['Internal', 'External']
group_max_requests:
description:
- Specifies the maximum number of simultaneous requests that are allowed to execute in the workload group.
type: int
required: false
importance:
description:
- Specifies the relative importance of a request in the workload group.
type: str
required: false
choices: ['Low', 'Medium', 'High']
max_dop:
description:
- Specifies the maximum degree of parallelism (MAXDOP) for parallel query execution.
type: int
required: false
request_max_cpu_time:
description:
- Specifies the maximum amount of CPU time, in seconds, that a request can use.
type: int
required: false
request_max_mem_grant_perc:
description:
- Specifies the maximum amount of memory that a single request can take from the pool.
type: int
required: false
request_mem_grant_timeout_sec:
description:
- Specifies the maximum time, in seconds, that a query can wait for a memory grant (work buffer memory) to become available.
type: int
required: false
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
- lowlydba.sqlserver.state
'''
EXAMPLES = r'''
- name: Enable resource governor
lowlydba.sqlserver.resource_governor:
sql_instance: sql-01.myco.io
enabled: true
- name: Create rg resource pool
lowlydba.sqlserver.rg_resource_pool:
sql_instance: sql-01.myco.io
resource_pool: "rpLittle"
max_cpu_perc: 5
- name: Create rg workload group
lowlydba.sqlserver.rg_workload_group:
sql_instance: sql-01.myco.io
workload_group: rgMyGroup
resource_pool: rpLittle
resource_pool_type: Internal
max_dop: 2
state: present
'''
RETURN = r'''
data:
description: Output from the C(Set-DbaRgWorkloadGroup), C(New-DbaRgWorkloadGroup), or C(Remove-DbaRgWorkloadGroup) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,101 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
$spec = @{
supports_check_mode = $true
options = @{
new_name = @{type = 'str'; required = $false; }
password = @{type = 'str'; required = $false; no_log = $true }
enabled = @{type = 'bool'; required = $false; default = $true }
password_must_change = @{type = 'bool'; required = $false }
password_policy_enforced = @{type = 'bool'; required = $false }
password_expiration_enabled = @{type = 'bool'; required = $false }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$newName = $module.Params.new_name
if ($null -ne $module.Params.password) {
$secPassword = ConvertTo-SecureString -String $module.Params.password -AsPlainText -Force
}
$enabled = $module.Params.enabled
[nullable[bool]]$passwordMustChange = $module.Params.password_must_change
[nullable[bool]]$passwordExpirationEnabled = $module.Params.password_expiration_enabled
[nullable[bool]]$passwordPolicyEnforced = $module.Params.password_policy_enforced
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$sa = Get-DbaLogin -SqlInstance $SqlInstance -SqlCredential $sqlCredential -EnableException | Where-Object ID -eq 1
$setLoginSplat = @{ }
if ($null -ne $newName) {
$setLoginSplat.Add("NewName", $newName)
if ($sa.Name -ne $newName) {
$changed = $true
}
}
if ($null -ne $passwordExpirationEnabled) {
if ($sa.PasswordExpirationEnabled -ne $passwordExpirationEnabled) {
$changed = $true
}
if ($passwordExpirationEnabled -eq $true) {
$setLoginSplat.add("PasswordExpirationEnabled", $true)
}
}
if ($null -ne $passwordPolicyEnforced) {
if ($sa.PasswordPolicyEnforced -ne $passwordPolicyEnforced) {
$changed = $true
}
if ($passwordPolicyEnforced -eq $true) {
$setLoginSplat.add("PasswordPolicyEnforced", $true)
}
}
if ($true -eq $passwordMustChange) {
if ($sa.PasswordMustChange -ne $passwordMustChange) {
$changed = $true
}
if ($passwordMustChange -eq $true) {
$setLoginSplat.add("PasswordMustChange", $true)
}
}
if ($null -ne $secPassword) {
$setLoginSplat.add("SecurePassword", $secPassword)
}
if ($enabled -eq $false) {
$disabled = $true
$setLoginSplat.add("Disable", $true)
}
else {
$disabled = $false
$setLoginSplat.add("Enable", $true)
}
# Check for changes
if (($changed -eq $true) -or ($disabled -ne $sa.IsDisabled) -or ($secPassword)) {
$output = $sa | Set-DbaLogin @setLoginSplat -WhatIf:$checkMode -EnableException
$module.Result.changed = $true
}
else {
$output = $sa
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.exitJson()
}
catch {
$module.FailJson("Configuring 'sa' login failed: $($_.Exception.Message)", $_)
}

View File

@@ -0,0 +1,74 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: sa
short_description: Configure the C(sa) login for security best practices
description:
- Rename, disable, and reset the password for the C(sa) login on a SQL Server instance per best practices.
options:
password:
description:
- Password for the login.
type: str
required: false
new_name:
description:
- The new name to rename the C(sa) login to.
type: str
required: false
enabled:
description:
- Whether the login is enabled or disabled.
type: bool
required: false
default: true
version_added: '0.4.0'
password_must_change:
description:
- Enforces user must change password at next login.
- When specified, will enforce I(password_expiration_enabled) and I(password_policy_enforced) as they are required.
type: bool
required: false
password_policy_enforced:
description:
- Enforces password complexity policy.
type: bool
required: false
password_expiration_enabled:
description:
- Enforces password expiration policy. Requires I(password_policy_enforced=true).
type: bool
required: false
version_added: 0.3.0
author: "John McCall (@lowlydba)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Disable sa login
lowlydba.sqlserver.sa:
sql_instance: sql-01.myco.io
disable: true
- name: Rename sa login
lowlydba.sqlserver.sa:
sql_instance: sql-01.myco.io
new_name: 'notthesayourelookingfor'
'''
RETURN = r'''
data:
description: Output from the C(Set-DbaLogin) function.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,59 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# (c) 2021, Sudhir Koduri (@kodurisudhir)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
# Get Csharp utility module
$spec = @{
supports_check_mode = $true
options = @{
name = @{type = 'str'; required = $true }
value = @{type = 'int'; required = $true }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$name = $module.Params.name
$value = $module.Params.value
$checkMode = $module.CheckMode
$module.Result.changed = $false
try {
$existingConfig = Get-DbaSpConfigure -SqlInstance $sqlInstance -SqlCredential $sqlCredential -Name $name -EnableException
if ($existingConfig.ConfiguredValue -ne $value) {
$setSpConfigureSplat = @{
SqlInstance = $sqlInstance
SqlCredential = $sqlCredential
Name = $name
Value = $value
WhatIf = $checkMode
EnableException = $true
}
$output = Set-DbaSpConfigure @setSpConfigureSplat
if ($existingConfig.IsDynamic -eq $false) {
$output | Add-Member -MemberType NoteProperty -Name "RestartRequired" -Value $true
}
$module.Result.changed = $true
}
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("sp_configure change failed.", $_)
}

View File

@@ -0,0 +1,50 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# (c) 2021, Sudhir Koduri (@kodurisudhir)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: sp_configure
short_description: Make instance level system configuration changes via C(sp_configure)
description:
- Read instance level system configuration for a given configuration and update to a new value as provided.
version_added: 0.1.0
options:
name:
description:
- Name of the configuration that will be changed.
type: str
required: true
value:
description:
- New value the configuration will be set to.
type: int
required: true
author: "Sudhir Koduri (@kodurisudhir)"
requirements:
- L(dbatools,https://www.powershellgallery.com/packages/dbatools/) PowerShell module
extends_documentation_fragment:
- lowlydba.sqlserver.sql_credentials
- lowlydba.sqlserver.attributes.check_mode
- lowlydba.sqlserver.attributes.platform_all
'''
EXAMPLES = r'''
- name: Enable remote DAC connection
lowlydba.sqlserver.sp_configure:
sql_instance: sql-01.myco.io
name: RemoteDacConnectionsEnabled
value: 1
'''
RETURN = r'''
data:
description:
- Output from the C(Set-DbaSpConfigure) function.
- RestartRequired returned if the setting requires a service restart to take effect.
returned: success, but not in check_mode.
type: dict
'''

View File

@@ -0,0 +1,57 @@
#!powershell
# -*- coding: utf-8 -*-
# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="1.1.112" }
$ErrorActionPreference = "Stop"
# Get Csharp utility module
$spec = @{
supports_check_mode = $true
options = @{
database = @{type = 'str'; required = $true }
local_file = @{type = 'str'; required = $false }
force = @{type = 'bool'; required = $false; default = $false }
}
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$localFile = $module.Params.local_file
$force = $module.Params.force
$checkMode = $module.CheckMode
$module.Result.changed = $false
$whoIsActiveSplat = @{
SqlInstance = $SqlInstance
SqlCredential = $SqlCredential
Database = $Database
WhatIf = $checkMode
Force = $force
Confirm = $false
EnableException = $true
}
if ($null -ne $LocalFile) {
$whoIsActiveSplat.LocalFile = $LocalFile
}
try {
$output = Install-DbaWhoIsActive @whoIsActiveSplat
$module.Result.changed = $true
if ($null -ne $output) {
$resultData = ConvertTo-SerializableObject -InputObject $output
$module.Result.data = $resultData
}
$module.ExitJson()
}
catch {
$module.FailJson("Installing sp_WhoIsActive failed.", $_)
}

Some files were not shown because too many files have changed in this diff Show More