summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/DOCUMENTATION.yml2
-rw-r--r--examples/ansible.cfg228
-rw-r--r--examples/hosts34
-rw-r--r--examples/hosts.yaml43
l---------examples/hosts.yml1
-rw-r--r--examples/scripts/ConfigureRemotingForAnsible.ps188
-rwxr-xr-xexamples/scripts/uptime.py105
-rwxr-xr-xexamples/scripts/yaml_to_ini.py207
8 files changed, 382 insertions, 326 deletions
diff --git a/examples/DOCUMENTATION.yml b/examples/DOCUMENTATION.yml
index 1272f13c7f..86f9c9462f 100644
--- a/examples/DOCUMENTATION.yml
+++ b/examples/DOCUMENTATION.yml
@@ -15,7 +15,7 @@ notes:
requirements:
- list of required things
- like the factor package
- - or a specic platform
+ - or a specific platform
options:
# One or more of the following
option_name:
diff --git a/examples/ansible.cfg b/examples/ansible.cfg
index 49da6f098d..4b4262305a 100644
--- a/examples/ansible.cfg
+++ b/examples/ansible.cfg
@@ -1,7 +1,7 @@
# config file for ansible -- http://ansible.com/
# ==============================================
-# nearly all parameters can be overridden in ansible-playbook
+# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
@@ -11,18 +11,19 @@
# some basic default values...
-inventory = /etc/ansible/hosts
+#inventory = /etc/ansible/hosts
#library = /usr/share/my_modules/
-remote_tmp = $HOME/.ansible/tmp
-pattern = *
-forks = 5
-poll_interval = 15
-sudo_user = root
+#remote_tmp = $HOME/.ansible/tmp
+#local_tmp = $HOME/.ansible/tmp
+#forks = 5
+#poll_interval = 15
+#sudo_user = root
#ask_sudo_pass = True
#ask_pass = True
-transport = smart
+#transport = smart
#remote_port = 22
-module_lang = C
+#module_lang = C
+#module_set_locale = False
# plays will gather facts by default, which contain information about
# the remote system.
@@ -30,7 +31,27 @@ module_lang = C
# smart - gather by default, but don't regather if already gathered
# implicit - gather by default, turn off with gather_facts: False
# explicit - do not gather by default, must say gather_facts: True
-gathering = implicit
+#gathering = implicit
+
+# This only affects the gathering done by a play's gather_facts directive,
+# by default gathering retrieves all facts subsets
+# all - gather all subsets
+# network - gather min and network facts
+# hardware - gather hardware facts (longest facts to retrieve)
+# virtual - gather min and virtual facts
+# facter - import facts from facter
+# ohai - import facts from ohai
+# You can combine them using comma (ex: network,virtual)
+# You can negate them using ! (ex: !hardware,!facter,!ohai)
+# A minimal set of facts is always gathered.
+#gather_subset = all
+
+# some hardware related facts are collected
+# with a maximum timeout of 10 seconds. This
+# option lets you increase or decrease that
+# timeout to something more suitable for the
+# environment.
+# gather_timeout = 10
# additional paths to search for roles in, colon separated
#roles_path = /etc/ansible/roles
@@ -39,19 +60,29 @@ gathering = implicit
#host_key_checking = False
# change the default callback
-#callback_stdout = skippy
+#stdout_callback = skippy
# enable additional callbacks
#callback_whitelist = timer, mail
+# Determine whether includes in tasks and handlers are "static" by
+# default. As of 2.0, includes are dynamic by default. Setting these
+# values to True will make includes behave more like they did in the
+# 1.x versions.
+#task_includes_static = True
+#handler_includes_static = True
+
+# Controls if a missing handler for a notification event is an error or a warning
+#error_on_missing_handler = True
+
# change this for alternative sudo implementations
-sudo_exe = sudo
+#sudo_exe = sudo
# What flags to pass to sudo
# WARNING: leaving out the defaults might create unexpected behaviours
-#sudo_flags = -H -k
+#sudo_flags = -H -S -n
# SSH timeout
-timeout = 10
+#timeout = 10
# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
@@ -82,24 +113,39 @@ timeout = 10
# list any Jinja2 extensions to enable here:
#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n
-# if set, always use this private key file for authentication, same as
+# if set, always use this private key file for authentication, same as
# if passing --private-key to ansible or ansible-playbook
#private_key_file = /path/to/file
+# If set, configures the path to the Vault password file as an alternative to
+# specifying --vault-password-file on the command line.
+#vault_password_file = /path/to/vault_password_file
+
# format of string {{ ansible_managed }} available within Jinja2
# templates indicates to users editing templates files will be replaced.
# replacing {file}, {host} and {uid} and strftime codes with proper values.
#ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
-# This short version is better used in templates as it won't flag the file as changed every run.
-ansible_managed = Ansible managed: {file} on {host}
+# {file}, {host}, {uid}, and the timestamp can all interfere with idempotence
+# in some situations so the default is a static string:
+#ansible_managed = Ansible managed
# by default, ansible-playbook will display "Skipping [host]" if it determines a task
-# should not be run on a host. Set this to "False" if you don't want to see these "Skipping"
-# messages. NOTE: the task header will still be shown regardless of whether or not the
+# should not be run on a host. Set this to "False" if you don't want to see these "Skipping"
+# messages. NOTE: the task header will still be shown regardless of whether or not the
# task is skipped.
#display_skipped_hosts = True
-# by default (as of 1.3), Ansible will raise errors when attempting to dereference
+# by default, if a task in a playbook does not include a name: field then
+# ansible-playbook will construct a header that includes the task's action but
+# not the task's args. This is a security feature because ansible cannot know
+# if the *module* considers an argument to be no_log at the time that the
+# header is printed. If your environment doesn't have a problem securing
+# stdout from ansible-playbook (or you have manually specified no_log in your
+# playbook on all of the tasks where you have secret information) then you can
+# safely set this to True to get more informative messages.
+#display_args_to_stdout = False
+
+# by default (as of 1.3), Ansible will raise errors when attempting to dereference
# Jinja2 variables that are not set in templates or action lines. Uncomment this line
# to revert the behavior to pre-1.3.
#error_on_undefined_vars = False
@@ -118,7 +164,7 @@ ansible_managed = Ansible managed: {file} on {host}
# (as of 1.8), Ansible can optionally warn when usage of the shell and
# command module appear to be simplified by using a default Ansible module
# instead. These warnings can be silenced by adjusting the following
-# setting or adding warn=yes or warn=no to the end of the command line
+# setting or adding warn=yes or warn=no to the end of the command line
# parameter string. This will for example suggest using the git module
# instead of shelling out to the git command.
# command_warnings = False
@@ -126,47 +172,50 @@ ansible_managed = Ansible managed: {file} on {host}
# set plugin path directories here, separate with colons
#action_plugins = /usr/share/ansible/plugins/action
+#cache_plugins = /usr/share/ansible/plugins/cache
#callback_plugins = /usr/share/ansible/plugins/callback
#connection_plugins = /usr/share/ansible/plugins/connection
#lookup_plugins = /usr/share/ansible/plugins/lookup
+#inventory_plugins = /usr/share/ansible/plugins/inventory
#vars_plugins = /usr/share/ansible/plugins/vars
#filter_plugins = /usr/share/ansible/plugins/filter
#test_plugins = /usr/share/ansible/plugins/test
+#strategy_plugins = /usr/share/ansible/plugins/strategy
# by default callbacks are not loaded for /bin/ansible, enable this if you
-# want, for example, a notification or logging callback to also apply to
+# want, for example, a notification or logging callback to also apply to
# /bin/ansible runs
#bin_ansible_callbacks = False
# don't like cows? that's unfortunate.
-# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
+# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
#nocows = 1
+# set which cowsay stencil you'd like to use by default. When set to 'random',
+# a random stencil will be selected for each task. The selection will be filtered
+# against the `cow_whitelist` option below.
+#cow_selection = default
+#cow_selection = random
+
+# when using the 'random' option for cowsay, stencils will be restricted to this list.
+# it should be formatted as a comma-separated list with no spaces between names.
+# NOTE: line continuations here are for formatting purposes only, as the INI parser
+# in python does not support them.
+#cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,\
+# hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,\
+# stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www
+
# don't like colors either?
# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
#nocolor = 1
-# the CA certificate path used for validating SSL certs. This path
-# should exist on the controlling node, not the target nodes
-# common locations:
-# RHEL/CentOS: /etc/pki/tls/certs/ca-bundle.crt
-# Fedora : /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
-# Ubuntu : /usr/share/ca-certificates/cacert.org/cacert.org.crt
-#ca_file_path =
-
-# the http user-agent string to use when fetching urls. Some web server
-# operators block the default urllib user agent as it is frequently used
-# by malicious attacks/scripts, so we set it to something unique to
-# avoid issues.
-#http_user_agent = ansible-agent
-
# if set to a persistent type (not 'memory', for example 'redis') fact values
# from previous runs in Ansible will be stored. This may be useful when
# wanting to use, for example, IP information from one group of servers
# without having to talk to them in the same playbook run to get their
# current IP information.
-fact_caching = memory
+#fact_caching = memory
# retry files
@@ -177,12 +226,50 @@ fact_caching = memory
#retry_files_enabled = False
#retry_files_save_path = ~/.ansible-retry
+# squash actions
+# Ansible can optimise actions that call modules with list parameters
+# when looping. Instead of calling the module once per with_ item, the
+# module is called once with all items at once. Currently this only works
+# under limited circumstances, and only with parameters named 'name'.
+#squash_actions = apk,apt,dnf,homebrew,package,pacman,pkgng,yum,zypper
# prevents logging of task data, off by default
#no_log = False
# prevents logging of tasks, but only on the targets, data is still logged on the master/controller
-#no_target_syslog = True
+#no_target_syslog = False
+
+# controls whether Ansible will raise an error or warning if a task has no
+# choice but to create world readable temporary files to execute a module on
+# the remote machine. This option is False by default for security. Users may
+# turn this on to have behaviour more like Ansible prior to 2.1.x. See
+# https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user
+# for more secure ways to fix this than enabling this option.
+#allow_world_readable_tmpfiles = False
+
+# controls the compression level of variables sent to
+# worker processes. At the default of 0, no compression
+# is used. This value must be an integer from 0 to 9.
+#var_compression_level = 9
+
+# controls what compression method is used for new-style ansible modules when
+# they are sent to the remote system. The compression types depend on having
+# support compiled into both the controller's python and the client's python.
+# The names should match with the python Zipfile compression types:
+# * ZIP_STORED (no compression. available everywhere)
+# * ZIP_DEFLATED (uses zlib, the default)
+# These values may be set per host via the ansible_module_compression inventory
+# variable
+#module_compression = 'ZIP_DEFLATED'
+
+# This controls the cutoff point (in bytes) on --diff for files
+# set to 0 for unlimited (RAM may suffer!).
+#max_diff_size = 1048576
+
+# This controls how ansible handles multiple --tags and --skip-tags arguments
+# on the CLI. If this is True then multiple arguments are merged together. If
+# it is False, then the last specified argument is used and the others are ignored.
+#merge_multiple_cli_flags = False
[privilege_escalation]
#become=True
@@ -204,34 +291,43 @@ fact_caching = memory
[ssh_connection]
# ssh arguments to use
-# Leaving off ControlPersist will result in poor performance, so use
-# paramiko on older platforms rather than removing it
-#ssh_args = -o ControlMaster=auto -o ControlPersist=60s
+# Leaving off ControlPersist will result in poor performance, so use
+# paramiko on older platforms rather than removing it, -C controls compression use
+#ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
+
+# The base directory for the ControlPath sockets.
+# This is the "%(directory)s" in the control_path option
+#
+# Example:
+# control_path_dir = /tmp/.ansible/cp
+#control_path_dir = $HOME/.ansible/cp
# The path to use for the ControlPath sockets. This defaults to
# "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with
-# very long hostnames or very long path names (caused by long user names or
+# very long hostnames or very long path names (caused by long user names or
# deeply nested home directories) this can exceed the character limit on
-# file socket names (108 characters for most platforms). In that case, you
+# file socket names (108 characters for most platforms). In that case, you
# may wish to shorten the string below.
-#
-# Example:
+#
+# Example:
# control_path = %(directory)s/%%h-%%r
#control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r
-# Enabling pipelining reduces the number of SSH operations required to
-# execute a module on the remote server. This can result in a significant
-# performance improvement when enabled, however when using "sudo:" you must
+# Enabling pipelining reduces the number of SSH operations required to
+# execute a module on the remote server. This can result in a significant
+# performance improvement when enabled, however when using "sudo:" you must
# first disable 'requiretty' in /etc/sudoers
#
# By default, this option is disabled to preserve compatibility with
# sudoers configurations that have requiretty (the default on many distros).
-#
+#
#pipelining = False
-# if True, make ansible use scp if the connection type is ssh
-# (default is sftp)
-#scp_if_ssh = True
+# Control the mechanism for transfering files
+# * smart = try sftp and then try scp [default]
+# * True = use scp only
+# * False = use sftp only
+#scp_if_ssh = smart
# if False, sftp will not use batch mode to transfer files. This may cause some
# types of file transfer failures impossible to catch however, and should
@@ -239,13 +335,13 @@ fact_caching = memory
#sftp_batch_mode = False
[accelerate]
-accelerate_port = 5099
-accelerate_timeout = 30
-accelerate_connect_timeout = 5.0
+#accelerate_port = 5099
+#accelerate_timeout = 30
+#accelerate_connect_timeout = 5.0
# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
-accelerate_daemon_timeout = 30
+#accelerate_daemon_timeout = 30
# If set to yes, accelerate_multi_key will allow multiple
# private keys to be uploaded to it, though each user must
@@ -258,3 +354,21 @@ accelerate_daemon_timeout = 30
# the default behaviour that copies the existing context or uses the user default
# needs to be changed to use the file system dependent context.
#special_context_filesystems=nfs,vboxsf,fuse,ramfs
+
+# Set this to yes to allow libvirt_lxc connections to work without SELinux.
+#libvirt_lxc_noseclabel = yes
+
+[colors]
+#highlight = white
+#verbose = blue
+#warn = bright purple
+#error = red
+#debug = dark gray
+#deprecate = purple
+#skip = cyan
+#unreachable = red
+#ok = green
+#changed = yellow
+#diff_add = green
+#diff_remove = red
+#diff_lines = cyan
diff --git a/examples/hosts b/examples/hosts
index ce4cbb7caa..841f4bc650 100644
--- a/examples/hosts
+++ b/examples/hosts
@@ -10,35 +10,35 @@
# Ex 1: Ungrouped hosts, specify before any group headers.
-green.example.com
-blue.example.com
-192.168.100.1
-192.168.100.10
+## green.example.com
+## blue.example.com
+## 192.168.100.1
+## 192.168.100.10
# Ex 2: A collection of hosts belonging to the 'webservers' group
-[webservers]
-alpha.example.org
-beta.example.org
-192.168.1.100
-192.168.1.110
+## [webservers]
+## alpha.example.org
+## beta.example.org
+## 192.168.1.100
+## 192.168.1.110
# If you have multiple hosts following a pattern you can specify
# them like this:
-www[001:006].example.com
+## www[001:006].example.com
# Ex 3: A collection of database servers in the 'dbservers' group
-[dbservers]
-
-db01.intranet.mydomain.net
-db02.intranet.mydomain.net
-10.25.1.56
-10.25.1.57
+## [dbservers]
+##
+## db01.intranet.mydomain.net
+## db02.intranet.mydomain.net
+## 10.25.1.56
+## 10.25.1.57
# Here's another example of host ranges, this time there are no
# leading 0s:
-db-[99:101]-node.example.com
+## db-[99:101]-node.example.com
diff --git a/examples/hosts.yaml b/examples/hosts.yaml
new file mode 100644
index 0000000000..0cb42f5bb0
--- /dev/null
+++ b/examples/hosts.yaml
@@ -0,0 +1,43 @@
+# This is the default ansible 'hosts' file.
+#
+# It should live in /etc/ansible/hosts
+#
+# - Comments begin with the '#' character
+# - Blank lines are ignored
+# - Top level entries are assumed to be groups
+# - Hosts must be specified in a group's hosts:
+# and they must be a key (: terminated)
+# - groups can have children, hosts and vars keys
+# - Anything defined under a hosts is assumed to be a var
+# - You can enter hostnames or ip addresses
+# - A hostname/ip can be a member of multiple groups
+# Ex 1: Ungrouped hosts, put in 'ungrouped' group
+##ungrouped:
+## hosts:
+## green.example.com:
+## ansible_ssh_host: 191.168.100.32
+## blue.example.com:
+## 192.168.100.1:
+## 192.168.100.10:
+
+# Ex 2: A collection of hosts belonging to the 'webservers' group
+
+##webservers:
+## hosts:
+## alpha.example.org:
+## beta.example.org:
+## 192.168.1.100:
+## 192.168.1.110:
+
+# Ex 3: You can create hosts using ranges and add children groups and vars to a group
+# The child group can define anything you would normally add to a group
+
+##testing:
+## hosts:
+## www[001:006].example.com:
+## vars:
+## testing1: value1
+## children:
+## webservers:
+## hosts:
+## beta.example.org:
diff --git a/examples/hosts.yml b/examples/hosts.yml
new file mode 120000
index 0000000000..bd6024a93b
--- /dev/null
+++ b/examples/hosts.yml
@@ -0,0 +1 @@
+hosts.yaml \ No newline at end of file
diff --git a/examples/scripts/ConfigureRemotingForAnsible.ps1 b/examples/scripts/ConfigureRemotingForAnsible.ps1
index a67ea8afb2..fcd4ab6d5f 100644
--- a/examples/scripts/ConfigureRemotingForAnsible.ps1
+++ b/examples/scripts/ConfigureRemotingForAnsible.ps1
@@ -1,33 +1,46 @@
-# Configure a Windows host for remote management with Ansible
+# Configure a Windows host for remote management with Ansible
# -----------------------------------------------------------
#
# This script checks the current WinRM/PSRemoting configuration and makes the
# necessary changes to allow Ansible to connect, authenticate and execute
# PowerShell commands.
-#
+#
# Set $VerbosePreference = "Continue" before running the script in order to
# see the output messages.
+# Set $SkipNetworkProfileCheck to skip the network profile check. Without
+# specifying this the script will only run if the device's interfaces are in
+# DOMAIN or PRIVATE zones. Provide this switch if you want to enable winrm on
+# a device with an interface in PUBLIC zone.
+#
+# Set $ForceNewSSLCert if the system has been syspreped and a new SSL Cert
+# must be forced on the WinRM Listener when re-running this script. This
+# is necessary when a new SID and CN name is created.
#
# Written by Trond Hindenes <trond@hindenes.com>
# Updated by Chris Church <cchurch@ansible.com>
+# Updated by Michael Crilly <mike@autologic.cm>
+# Updated by Anton Ouzounov <Anton.Ouzounov@careerbuilder.com>
#
# Version 1.0 - July 6th, 2014
# Version 1.1 - November 11th, 2014
+# Version 1.2 - May 15th, 2015
+# Version 1.3 - April 4th, 2016
Param (
[string]$SubjectName = $env:COMPUTERNAME,
[int]$CertValidityDays = 365,
- $CreateSelfSignedCert = $true
+ [switch]$SkipNetworkProfileCheck,
+ $CreateSelfSignedCert = $true,
+ [switch]$ForceNewSSLCert
)
-
Function New-LegacySelfSignedCert
{
Param (
[string]$SubjectName,
[int]$ValidDays = 365
)
-
+
$name = New-Object -COM "X509Enrollment.CX500DistinguishedName.1"
$name.Encode("CN=$SubjectName", 0)
@@ -60,11 +73,12 @@ Function New-LegacySelfSignedCert
$certdata = $enrollment.CreateRequest(0)
$enrollment.InstallResponse(2, $certdata, 0, "")
- # Return the thumbprint of the last installed cert.
+ # Return the thumbprint of the last installed certificate;
+ # This is needed for the new HTTPS WinRM listerner we're
+ # going to create further down.
Get-ChildItem "Cert:\LocalMachine\my"| Sort-Object NotBefore -Descending | Select -First 1 | Select -Expand Thumbprint
}
-
# Setup error handling.
Trap
{
@@ -73,14 +87,12 @@ Trap
}
$ErrorActionPreference = "Stop"
-
# Detect PowerShell version.
If ($PSVersionTable.PSVersion.Major -lt 3)
{
Throw "PowerShell version 3 or higher is required."
}
-
# Find and start the WinRM service.
Write-Verbose "Verifying WinRM service."
If (!(Get-Service "WinRM"))
@@ -91,14 +103,21 @@ ElseIf ((Get-Service "WinRM").Status -ne "Running")
{
Write-Verbose "Starting WinRM service."
Start-Service -Name "WinRM" -ErrorAction Stop
+ Write-Verbose "Setting WinRM service to start automatically on boot."
+ Set-Service -Name "WinRM" -StartupType Automatic
}
-
# WinRM should be running; check that we have a PS session config.
If (!(Get-PSSessionConfiguration -Verbose:$false) -or (!(Get-ChildItem WSMan:\localhost\Listener)))
{
- Write-Verbose "Enabling PS Remoting."
+ if ($SkipNetworkProfileCheck) {
+ Write-Verbose "Enabling PS Remoting without checking Network profile."
+ Enable-PSRemoting -SkipNetworkProfileCheck -Force -ErrorAction Stop
+ }
+ else {
+ Write-Verbose "Enabling PS Remoting"
Enable-PSRemoting -Force -ErrorAction Stop
+ }
}
Else
{
@@ -112,17 +131,19 @@ If (!($listeners | Where {$_.Keys -like "TRANSPORT=HTTPS"}))
# HTTPS-based endpoint does not exist.
If (Get-Command "New-SelfSignedCertificate" -ErrorAction SilentlyContinue)
{
- $cert = New-SelfSignedCertificate -DnsName $env:COMPUTERNAME -CertStoreLocation "Cert:\LocalMachine\My"
+ $cert = New-SelfSignedCertificate -DnsName $SubjectName -CertStoreLocation "Cert:\LocalMachine\My"
$thumbprint = $cert.Thumbprint
+ Write-Host "Self-signed SSL certificate generated; thumbprint: $thumbprint"
}
Else
{
- $thumbprint = New-LegacySelfSignedCert -SubjectName $env:COMPUTERNAME
+ $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName
+ Write-Host "(Legacy) Self-signed SSL certificate generated; thumbprint: $thumbprint"
}
# Create the hashtables of settings to be used.
$valueset = @{}
- $valueset.Add('Hostname', $env:COMPUTERNAME)
+ $valueset.Add('Hostname', $SubjectName)
$valueset.Add('CertificateThumbprint', $thumbprint)
$selectorset = @{}
@@ -135,9 +156,38 @@ If (!($listeners | Where {$_.Keys -like "TRANSPORT=HTTPS"}))
Else
{
Write-Verbose "SSL listener is already active."
+
+ # Force a new SSL cert on Listener if the $ForceNewSSLCert
+ if($ForceNewSSLCert){
+
+ # Create the new cert.
+ If (Get-Command "New-SelfSignedCertificate" -ErrorAction SilentlyContinue)
+ {
+ $cert = New-SelfSignedCertificate -DnsName $SubjectName -CertStoreLocation "Cert:\LocalMachine\My"
+ $thumbprint = $cert.Thumbprint
+ Write-Host "Self-signed SSL certificate generated; thumbprint: $thumbprint"
+ }
+ Else
+ {
+ $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName
+ Write-Host "(Legacy) Self-signed SSL certificate generated; thumbprint: $thumbprint"
+ }
+
+ $valueset = @{}
+ $valueset.Add('Hostname', $SubjectName)
+ $valueset.Add('CertificateThumbprint', $thumbprint)
+
+ # Delete the listener for SSL
+ $selectorset = @{}
+ $selectorset.Add('Transport', 'HTTPS')
+ $selectorset.Add('Address', '*')
+ Remove-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset
+
+ # Add new Listener with new SSL cert
+ New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
+ }
}
-
# Check for basic authentication.
$basicAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where {$_.Name -eq "Basic"}
If (($basicAuthSetting.Value) -eq $false)
@@ -150,7 +200,6 @@ Else
Write-Verbose "Basic auth is already enabled."
}
-
# Configure firewall to allow WinRM HTTPS connections.
$fwtest1 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS"
$fwtest2 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS" profile=any
@@ -177,19 +226,18 @@ $httpsResult = New-PSSession -UseSSL -ComputerName "localhost" -SessionOption $h
If ($httpResult -and $httpsResult)
{
- Write-Verbose "HTTP and HTTPS sessions are enabled."
+ Write-Verbose "HTTP: Enabled | HTTPS: Enabled"
}
ElseIf ($httpsResult -and !$httpResult)
{
- Write-Verbose "HTTP sessions are disabled, HTTPS session are enabled."
+ Write-Verbose "HTTP: Disabled | HTTPS: Enabled"
}
ElseIf ($httpResult -and !$httpsResult)
{
- Write-Verbose "HTTPS sessions are disabled, HTTP session are enabled."
+ Write-Verbose "HTTP: Enabled | HTTPS: Disabled"
}
Else
{
Throw "Unable to establish an HTTP or HTTPS remoting session."
}
-
Write-Verbose "PS Remoting has been successfully configured for Ansible."
diff --git a/examples/scripts/uptime.py b/examples/scripts/uptime.py
index 167dedcede..3ea6725b75 100755
--- a/examples/scripts/uptime.py
+++ b/examples/scripts/uptime.py
@@ -1,31 +1,88 @@
-#!/usr/bin/python
-# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
-# example of getting the uptime of all hosts, 10 at a time
+#!/usr/bin/env python
+from collections import namedtuple
+from ansible.parsing.dataloader import DataLoader
+from ansible.vars import VariableManager
+from ansible.inventory import Inventory
+from ansible.playbook.play import Play
+from ansible.executor.task_queue_manager import TaskQueueManager
+from ansible.plugins.callback import CallbackBase
-import ansible.runner
-import sys
+# Create a callback object so we can capture the output
+class ResultsCollector(CallbackBase):
-# construct the ansible runner and execute on all hosts
-results = ansible.runner.Runner(
- pattern='*', forks=10,
- module_name='command', module_args='/usr/bin/uptime',
-).run()
+ def __init__(self, *args, **kwargs):
+ super(ResultsCollector, self).__init__(*args, **kwargs)
+ self.host_ok = {}
+ self.host_unreachable = {}
+ self.host_failed = {}
-if results is None:
- print "No hosts found"
- sys.exit(1)
+ def v2_runner_on_unreachable(self, result):
+ self.host_unreachable[result._host.get_name()] = result
-print "UP ***********"
-for (hostname, result) in results['contacted'].items():
- if not 'failed' in result:
- print "%s >>> %s" % (hostname, result['stdout'])
+ def v2_runner_on_ok(self, result, *args, **kwargs):
+ self.host_ok[result._host.get_name()] = result
-print "FAILED *******"
-for (hostname, result) in results['contacted'].items():
- if 'failed' in result:
- print "%s >>> %s" % (hostname, result['msg'])
+ def v2_runner_on_failed(self, result, *args, **kwargs):
+ self.host_failed[result._host.get_name()] = result
-print "DOWN *********"
-for (hostname, result) in results['dark'].items():
- print "%s >>> %s" % (hostname, result)
+def main():
+ host_list = ['localhost', 'www.example.com', 'www.google.com']
+ Options = namedtuple('Options', ['connection','module_path', 'forks', 'remote_user',
+ 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
+ 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])
+
+ # initialize needed objects
+ variable_manager = VariableManager()
+ loader = DataLoader()
+ options = Options(connection='smart', module_path='/usr/share/ansible', forks=100,
+ remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
+ sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
+ become_user=None, verbosity=None, check=False)
+
+ passwords = dict()
+
+ # create inventory and pass to var manager
+ inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
+ variable_manager.set_inventory(inventory)
+
+ # create play with tasks
+ play_source = dict(
+ name = "Ansible Play",
+ hosts = host_list,
+ gather_facts = 'no',
+ tasks = [ dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime'))) ]
+ )
+ play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
+
+ # actually run it
+ tqm = None
+ callback = ResultsCollector()
+ try:
+ tqm = TaskQueueManager(
+ inventory=inventory,
+ variable_manager=variable_manager,
+ loader=loader,
+ options=options,
+ passwords=passwords,
+ )
+ tqm._stdout_callback = callback
+ result = tqm.run(play)
+ finally:
+ if tqm is not None:
+ tqm.cleanup()
+
+ print "UP ***********"
+ for host, result in callback.host_ok.items():
+ print '{} >>> {}'.format(host, result._result['stdout'])
+
+ print "FAILED *******"
+ for host, result in callback.host_failed.items():
+ print '{} >>> {}'.format(host, result._result['msg'])
+
+ print "DOWN *********"
+ for host, result in callback.host_unreachable.items():
+ print '{} >>> {}'.format(host, result._result['msg'])
+
+if __name__ == '__main__':
+ main()
diff --git a/examples/scripts/yaml_to_ini.py b/examples/scripts/yaml_to_ini.py
deleted file mode 100755
index 981176b2f2..0000000000
--- a/examples/scripts/yaml_to_ini.py
+++ /dev/null
@@ -1,207 +0,0 @@
-# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
-#
-# This file is part of Ansible
-#
-# Ansible is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# Ansible is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
-
-import ansible.constants as C
-from ansible.inventory.host import Host
-from ansible.inventory.group import Group
-from ansible import errors
-from ansible import utils
-import os
-import yaml
-import sys
-from six import iteritems
-
-class InventoryParserYaml(object):
- ''' Host inventory parser for ansible '''
-
- def __init__(self, filename=C.DEFAULT_HOST_LIST):
-
- sys.stderr.write("WARNING: YAML inventory files are deprecated in 0.6 and will be removed in 0.7, to migrate" +
- " download and run https://github.com/ansible/ansible/blob/devel/examples/scripts/yaml_to_ini.py\n")
-
- fh = open(filename)
- data = fh.read()
- fh.close()
- self._hosts = {}
- self._parse(data)
-
- def _make_host(self, hostname):
-
- if hostname in self._hosts:
- return self._hosts[hostname]
- else:
- host = Host(hostname)
- self._hosts[hostname] = host
- return host
-
- # see file 'test/yaml_hosts' for syntax
-
- def _parse(self, data):
- # FIXME: refactor into subfunctions
-
- all = Group('all')
-
- ungrouped = Group('ungrouped')
- all.add_child_group(ungrouped)
-
- self.groups = dict(all=all, ungrouped=ungrouped)
- grouped_hosts = []
-
- yaml = utils.parse_yaml(data)
-
- # first add all groups
- for item in yaml:
- if type(item) == dict and 'group' in item:
- group = Group(item['group'])
-
- for subresult in item.get('hosts',[]):
-
- if type(subresult) in [ str, unicode ]:
- host = self._make_host(subresult)
- group.add_host(host)
- grouped_hosts.append(host)
- elif type(subresult) == dict:
- host = self._make_host(subresult['host'])
- vars = subresult.get('vars',{})
- if type(vars) == list:
- for subitem in vars:
- for (k,v) in subitem.items():
- host.set_variable(k,v)
- elif type(vars) == dict:
- for (k,v) in subresult.get('vars',{}).items():
- host.set_variable(k,v)
- else:
- raise errors.AnsibleError("unexpected type for variable")
- group.add_host(host)
- grouped_hosts.append(host)
-
- vars = item.get('vars',{})
- if type(vars) == dict:
- for (k,v) in item.get('vars',{}).items():
- group.set_variable(k,v)
- elif type(vars) == list:
- for subitem in vars:
- if type(subitem) != dict:
- raise errors.AnsibleError("expected a dictionary")
- for (k,v) in subitem.items():
- group.set_variable(k,v)
-
- self.groups[group.name] = group
- all.add_child_group(group)
-
- # add host definitions
- for item in yaml:
- if type(item) in [ str, unicode ]:
- host = self._make_host(item)
- if host not in grouped_hosts:
- ungrouped.add_host(host)
-
- elif type(item) == dict and 'host' in item:
- host = self._make_host(item['host'])
-
- vars = item.get('vars', {})
- if type(vars)==list:
- varlist, vars = vars, {}
- for subitem in varlist:
- vars.update(subitem)
- for (k,v) in vars.items():
- host.set_variable(k,v)
-
- groups = item.get('groups', {})
- if type(groups) in [ str, unicode ]:
- groups = [ groups ]
- if type(groups)==list:
- for subitem in groups:
- if subitem in self.groups:
- group = self.groups[subitem]
- else:
- group = Group(subitem)
- self.groups[group.name] = group
- all.add_child_group(group)
- group.add_host(host)
- grouped_hosts.append(host)
-
- if host not in grouped_hosts:
- ungrouped.add_host(host)
-
- # make sure ungrouped.hosts is the complement of grouped_hosts
- ungrouped_hosts = [host for host in ungrouped.hosts if host not in grouped_hosts]
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print "usage: yaml_to_ini.py /path/to/ansible/hosts"
- sys.exit(1)
-
- result = ""
-
- original = sys.argv[1]
- yamlp = InventoryParserYaml(filename=sys.argv[1])
- dirname = os.path.dirname(original)
-
- group_names = [ g.name for g in yamlp.groups.values() ]
-
- for group_name in sorted(group_names):
-
- record = yamlp.groups[group_name]
-
- if group_name == 'all':
- continue
-
- hosts = record.hosts
- result = result + "[%s]\n" % record.name
- for h in hosts:
- result = result + "%s\n" % h.name
- result = result + "\n"
-
- groupfiledir = os.path.join(dirname, "group_vars")
- if not os.path.exists(groupfiledir):
- print "* creating: %s" % groupfiledir
- os.makedirs(groupfiledir)
- groupfile = os.path.join(groupfiledir, group_name)
- print "* writing group variables for %s into %s" % (group_name, groupfile)
- groupfh = open(groupfile, 'w')
- groupfh.write(yaml.dump(record.get_variables()))
- groupfh.close()
-
- for (host_name, host_record) in iteritems(yamlp._hosts):
- hostfiledir = os.path.join(dirname, "host_vars")
- if not os.path.exists(hostfiledir):
- print "* creating: %s" % hostfiledir
- os.makedirs(hostfiledir)
- hostfile = os.path.join(hostfiledir, host_record.name)
- print "* writing host variables for %s into %s" % (host_record.name, hostfile)
- hostfh = open(hostfile, 'w')
- hostfh.write(yaml.dump(host_record.get_variables()))
- hostfh.close()
-
-
- # also need to keep a hash of variables per each host
- # and variables per each group
- # and write those to disk
-
- newfilepath = os.path.join(dirname, "hosts.new")
- fdh = open(newfilepath, 'w')
- fdh.write(result)
- fdh.close()
-
- print "* COMPLETE: review your new inventory file and replace your original when ready"
- print "* new inventory file saved as %s" % newfilepath
- print "* edit group specific variables in %s/group_vars/" % dirname
- print "* edit host specific variables in %s/host_vars/" % dirname
-
- # now need to write this to disk as (oldname).new
- # and inform the user