Use ansible to remotely restart mac machine

1, allow ssh connection on Mac machine:

systempreference ->sharing->remote inlogging-> allow users that can be remotely access to this machine

2, create yaml task file:

  - name: restart the mac host
    become: yes
    shell: sleep 2 && /sbin/shutdown -r now "Ansible restart the host"
    ansible_become_pass: sudopassword
    async: 1
    poll: 0
    ignore_errors: true

  - name: "Wait for reboot"
    local_action: wait_for host={{ ansible_default_ipv4.address }} port=22 delay=10 state=started
    become: false

“shutdown” command requires super user privilege, that can be achieved by become command, use ansible_become_pass to pass sudo password to the command. There is option to avoid writing sudo password in the yaml file, referring to ansible-vault.

Add “sleep 2” in front of the shutdown command to avoid “ssh connection lost” error when implement sensible-playbook, which will cause the interruption of the playbook.

After this task, set wait_for task applied on the local controller, to periodically check ssh connectivity of the remote Mac host.

 

 

Advertisements

Connect to Windows host using domain account from ansible controller not joined into AD domain

The discussion we had previously is only useful to manage a windows PC with local username/password. In order to manage a domain windows PC we have to install kerberos module for Ansible. I will give the guide regarding the setup of ansible controller to manage a domain windows PC while ansible controller itself is not within the domain.

1, Even through ansible controller is not necessary to join the domain, it is necessary that  machine of ansible controller can reach domain DNS and NTP services.  We can configure NTP server as the same domain NTP server if possible.

To get NTP used with windows host, enter “w32tm /query /peers” in cmd of window.

2, Join domain network, acquired IP address, WINS, DNS etc från domain network, this can happens automatically via DHCP when connected ansible controller to the domained network.

3, Install kerberos for ansible (example for Mac OS X)

pip install request kerberos
pip install pywinrm[kerberos]

4, Configure kerberos

edit etc/krb5.conf file, if krb5.conf is not existed, create one:

below is an example of krb5.conf file:

mac-c02t6npagtfj:etc grayin$ vi krb5.conf

        krb5_run_aklog = 1
        krb5_aklog_path = /usr/local/krb5/bin/aklog
        default_lifetime = 25h
        telnet = {
                autologin = 1
        }
        xdm = {
               retain_ccache = 1
                afs_retain_token = 1
        }
       pam = {
                ticket_lifetime = 90000
                renew_lifetime = 90000
                forwardable = true
        }
[libdefaults]
        forwardable = true
        default_realm = LFAD.LFNET.SE
[realms]
        DOMAIN.COM = {
                kdc = E00DC0008.DOMAIN.COM
                admin_server = E00DC0008.DOMAIN.COM
                default_domain = domain.com
        }
[domain_realm]
         .domain.com = DOMAIN.COM
         domain.com = DOMAIN.COM
[kdc]
        profile = /etc/kdc.conf
[logging]
        default = SYSLOG:INFO:LOCAL6

 

[realms] and [domain_realm] are the area where new domain information need to be added. Using echo %username% will allow you to identify the authenticating domain controller.If you just desire to identify which domain controller the user retrieved group policies from you can type gpresult /r.

5, Test kerberos connection

#kinit user@MY.DOMAIN.COM

#To see what tickets if any you have acquired, use the command klist

#klist

mac-c02t6npagtfj:ansible_test grayin$ kinit username@DOMAIN.COM
username@DOMAIN.COM's password: 

'mac-c02t6npagtfj:ansible_test grayin$ klist
Credentials cache: API:FA05485A-8E6B-45F8-9526-D4B4EEDA5D1D
        Principal: username@DOMAIN.COM
  Issued                Expires               Principal
Mar  8 14:49:48 2018  Mar  9 00:49:44 2018  krbtgt/DOMAIN.COM@DOMAIN.COM

Once you have a valid ticket, you can check to ensure that everything is working as expected from command line. To test this, make sure that your inventory looks like the following:

[windows]
win01.DOMAIN.COM

[windows:vars]
ansible_user = username@DOMAIN.COM
ansible_winrm_transport=kerberos
ansible_connection = winrm
ansible_port = 5986
# The following is necessary for Python 2.7.9+ when using default WinRM self-signed certificates:
ansible_winrm_server_cert_validation = ignore

Especially “ansible_winrm_transport” can be changed to ssl if you want to authenticate with a local account of windows PC.  When connecting to windows host there are several authentication options that can be used, refer to here

Option Local Accounts Active Directory Accounts Credential Delegation
Basic, ssl Yes No No
Certificate Yes No No
Kerberos No Yes Yes
NTLM Yes Yes No
CredSSP Yes Yes

6, Make sure that managed windows pc is listening on 5986 and the firewall on PC is turned off or traffic to/from port 5986 is allowed. To check the state of configuration settings, type winrm get winrm/config. To check if tcp 5986 is listening and no firewall blocking, type telnet win01 5986 from ansible controller.

It can be a very headache to turn off windows defenders when “off” button is grey i no matter windows security center or windows firewall&network, or windows defender. the most efficient way for me is to go directly to regedit and change value there.

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender find “start” value from domain/private/public separately and set the value from 1 to 0.

Of course you can allow winrm https 5986 application from firewall allow application setup. But this option is grey too in my test environment. Then we can try to change configuration from pgedit.msc, to use group policy editor to create incoming traffic rules for winrm:

Go to gpedit.msc, computer configuration ->windows settings ->security settings -> windows firewall with advanced security -> inbound rules add rules

7, T-SHOOT

In my test I got stuck in “password incorrect” message when set correct password in the inventory sensible_password=password, even though I am pretty sure that I have typed the correct password.

mac-c02t6npagtfj:ansible_test grayin$ ansible-playbook -i host main.yaml
PLAY [Hit a Specific Host on the Server] *************************************************************************************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************************************************************************************************************
fatal: [D75C0004.LFAD.LFNET.SE]: UNREACHABLE! => {"changed": false, "msg": "Kerberos auth failure: a940bf@LFAD.LFNET.SE's password: \nkinit: Password incorrect", "unreachable": true}
to retry, use: --limit @/Users/grayin/ansible_test/main.retry

Here is the discussion regarding this problem. It seems that  winrm module work if you get a kerberos token via kinit before executing ansible, even if the host isn’t joined to the domain. It fails though if you try to rely on the ansible_user/ansible_password combination.

I also encountered another problem that I must have account which owns administrative right for window computer in order to get connection successfully, Otherwise ansible kerberos connection will get error for either  time_out or credential refused or need paaeven though I have a valid kerberos toke listed by klist.

 

setup An Ansible Test Lab For Windows Managed hosts

I use Mac, and have setup a virtual window 10 host via VMware fusion. The target of the lab is to use ansible to restart windows 10 virtual host, after this, I have created a playbook to finish several tasks in this virtual host: test connection using win_ping, restart host using win_reboot, and visit a website using win_uri. The lab can be extended by adding new task into the playbook:

1, create host file (host inventory) in the folder /etc/ansible/hosts

#mkdir /etc/ansible

#touch /etc/ansible/hosts

#vi /etc/ansible/hosts

add IP address of the virtual host that will be connected remotely

2, create inventory file to save the other attributes. for example, create “windows.yml” to save username/password, the connection method used to manage windows hosts:

$ pwd

/users/username/ansible_test/group_vars

 

:group_vars grayin$ vi windows.yml

#It is suggested that these be encrypted with ansible-vault:

# ansible-vault edit group_vars/windows.yml

ansible_ssh_user: username

ansible_ssh_pass: password

ansible_ssh_port: 5986

ansible_connection: winrm

# The following is necessary for Python 2.7.9+ (or any older Python that has backported SSLContext, eg, Python 2.7.5 on RHEL7) when using default WinRM self-signed certificates:

ansible_winrm_server_cert_validation: ignore

Normally ansible uses ssh to communicate managed hosts, that means in order to manage windows host, windows need have ssh server enabled first. Here is a indication about the ways to enable ssh on windows 10

However ansible recommended to use Winrm to remotely manage windows hosts. Here is ansible document about winrm setup. In short, I did the following in my virtual window 10 machine, and then set ansbile_connection attribute to “winrm” in my above windows.yml file.

I did download file “ConfigureRemotingForAnsible.ps1” to the windows hosts. and run the following command in powershell.

$url = "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
$file = "$env:SystemDrive\temp\ConfigureRemotingForAnsible.ps1"

(New-Object -TypeName System.Net.WebClient).DownloadFile($url, $file)

powershell.exe -ExecutionPolicy ByPass -File $file

After this, I got 2 listener for http port 5895 and https 5896.

winrm enumerate winrm/config/Listener

This will output something like the following:

Listener
    Address = *
    Transport = HTTP
    Port = 5985
    Hostname
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint
    ListeningOn = 10.0.2.15, 127.0.0.1, 192.168.56.155, ::1, fe80::5efe:10.0.2.15%6, fe80::5efe:192.168.56.155%8, fe80::
ffff:ffff:fffe%2, fe80::203d:7d97:c2ed:ec78%3, fe80::e8ea:d765:2c69:7756%7

Listener
    Address = *
    Transport = HTTPS
    Port = 5986
    Hostname = SERVER2016
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint = E6CDAA82EEAF2ECE8546E05DB7F3E01AA47D76CE
    ListeningOn = 10.0.2.15, 127.0.0.1, 192.168.56.155, ::1, fe80::5efe:10.0.2.15%6, fe80::5efe:192.168.56.155%8, fe80::
ffff:ffff:fffe%2, fe80::203d:7d97:c2ed:ec78%3, fe80::e8ea:d765:2c69:7756%7

3, run testto window 10 using winrm connection. I use win_ping module, which is doing the similar thing as module “ping” towards linux/unix server

:ansible_test grayin$ ansible windows -i host -m win_ping

192.168.2.129 | SUCCESS => {

    “changed”: false, 

    “failed”: false, 

    “ping”: “pong”

}

4, test restart of windows 10 host by using module “win_reboot”

mac-c02t6npagtfj:ansible_test grayin$ ansible windows -i host -m win_reboot

192.168.2.129 | SUCCESS => {

    “changed”: true, 

    “elapsed”: 162, 

    “failed”: false, 

    “rebooted”: true

}

Now we have seen that virtual host is reboot and up again. Below I will create a playbook to implement several tasks one by one

5,create a file named as “test.yaml”

mac-c02t6npagtfj:ansible_test grayin$ vi test.yaml


- name: Hit a Specific Host on the Server

  hosts: 192.168.2.129

  vars:

    user: "username"

    password: "passoword"

  tasks:

 - name: ping host ok

    win_ping:

  - name: restart the host

    win_reboot:

   - name: get url

    win_uri:

      url: "http://www.google.com/"

      method: GET

  - name: Perform a HEAD on an Endpoint

    win_uri:

      url: http://www.google.se/

      method: HEAD

6, run playbook and get the following result:

mac-c02t6npagtfj:ansible_test grayin$ ansible-playbook -i group_vars/windows.yml -i host task.yaml

PLAY [Hit a Specific Host on the Server] **********************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************************************

ok: [192.168.2.129]

TASK [ping host ok] *******************************************************************************************************************************************

ok: [192.168.2.129]

TASK [restart the host] ***************************************************************************************************************************************

changed: [192.168.2.129]

TASK [get url] ************************************************************************************************************************************************

ok: [192.168.2.129]

TASK [Perform a HEAD on an Endpoint] **************************************************************************************************************************

ok: [192.168.2.129]

PLAY RECAP ****************************************************************************************************************************************************

192.168.2.129              : ok=5    changed=1    unreachable=0    failed=0

7, extend the playbook

We can add more management tasks into the playbook, ansible documents has listed all the available modules that can be used to manage windows hosts. More info can be found here.

Here is the blog regarding “setup An Ansible Test Lab For Windows Managed Nodes & Custom Windows Modules”

Install ansible in mac os

Ansible is mainly used for automize Linux/windows servers provisioning and operation, however from version 2.1 there is support module for network related devices.

In order to test it I have first install ansible in my mac:

There are several ways to install ansible, but the mostly common used on mac is homebrew an pip. Here is the comparision of both installation ways:

"pip is a packager for the python world – you should only ever be able to install python-things with it; homebrew is a package manager targetted at OSX; it doesn’t impose any restrictions onto what software you can install with it – since python is a subset of software.

installing things with brew will install them into /usr/local/;

installing things with pip will fetch packages from the Python Package Index, and it will install them in a place where your python interpreter will find them: either into your home directory (e.g. ~/.local/lib/python2.7/site-packages/) or in some global search-path of your python interpreter (e.g. /usr/local/lib/python2.7/dist-packages/)”

We will just explore the way to install ansible with homebrew:

1, install Xcode (C compiler) in order to use python
xcode-select –install

2, Install python using homebrew

brew install python

or

brew install python3

Actually, step 1 and 2 can be skipped because all new Mac OS X has python 2.7 installed already.

3, brew install ansible

After the installation we can find ansible is installed under /usr/local/bin/

mac-c02t6npagtfj:bin grayin$ ls ansible*

ansible ansible-doc ansible-pull

ansible-config ansible-galaxy ansible-vault

ansible-connection ansible-inventory

ansible-console ansible-playbook

notes: do “brew update” first before the installation to avoid any unexpected errors