본문 바로가기

IaC Application/ansible

ansible Windows

2022 구성

PS C:\Users\Administrator> $env:computername
JIWON-00

PS C:\Users\Administrator> Get-NetIPAddress


IPAddress         : ::1
InterfaceIndex    : 1
InterfaceAlias    : Loopback Pseudo-Interface 1
AddressFamily     : IPv6
Type              : Unicast
PrefixLength      : 128
PrefixOrigin      : WellKnown
SuffixOrigin      : WellKnown
AddressState      : Preferred
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore

IPAddress         : 200.200.200.149
InterfaceIndex    : 4
InterfaceAlias    : Ethernet0
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Preferred
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore

IPAddress         : 127.0.0.1
InterfaceIndex    : 1
InterfaceAlias    : Loopback Pseudo-Interface 1
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 8
PrefixOrigin      : WellKnown
SuffixOrigin      : WellKnown
AddressState      : Preferred
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore



PS C:\Users\Administrator> Get-NetAdapter

Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
----                      --------------------                    ------- ------       ----------             ---------
Ethernet0                 Intel(R) 82574L Gigabit Network Conn...       4 Up           00-0C-29-20-07-72         1 Gbps


--ip주소 초기화
PS C:\Users\Administrator> Set-NetIPInterface -InterfaceIndex 4 -Dhcp Enabled

PS C:\Users\Administrator> New-NetIPAddress -InterfaceIndex 4 -IPAddress 200.200.200.149 -PrefixLength 24 -DefaultGateway 200.200.200.254


IPAddress         : 200.200.200.149
InterfaceIndex    : 4
InterfaceAlias    : Ethernet0
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Tentative
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore

IPAddress         : 200.200.200.149
InterfaceIndex    : 4
InterfaceAlias    : Ethernet0
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Invalid
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : PersistentStore

PS C:\Users\Administrator> Set-DnsClientServerAddress -InterfaceIndex 4 -ServerAddresses "203.248.252.2, 8.8.8.8"

PS C:\Users\Administrator> ipconfig /all

Windows IP 구성

   호스트 이름 . . . . . . . . : jiwon-00
   주 DNS 접미사 . . . . . . . :
   노드 유형 . . . . . . . . . : 혼성
   IP 라우팅 사용. . . . . . . : 아니요
   WINS 프록시 사용. . . . . . : 아니요

이더넷 어댑터 Ethernet0:

   연결별 DNS 접미사. . . . :
   설명. . . . . . . . . . . . : Intel(R) 82574L Gigabit Network Connection
   물리적 주소 . . . . . . . . : 00-0C-29-20-07-72
   DHCP 사용 . . . . . . . . . : 아니요
   자동 구성 사용. . . . . . . : 예
   IPv4 주소 . . . . . . . . . : 200.200.200.149(기본 설정)
   서브넷 마스크 . . . . . . . : 255.255.255.0
   기본 게이트웨이 . . . . . . : 200.200.200.254
   DNS 서버. . . . . . . . . . : 203.248.252.2
                                 8.8.8.8
   Tcpip를 통한 NetBIOS. . . . : 사용

PS C:\Users\Administrator> mkdir c:\share


    디렉터리: C:\


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----      2024-03-25   오후 8:36                share


PS C:\Users\Administrator> net share shtest=c:\share
shtest이(가) 공유되었습니다.

PS C:\Users\Administrator>
--DNS 추가 CLI로
PS C:\Users\Administrator> Install-WindowsFeature dns -IncludeManagementTools
Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {DNS 서버, 원격 서버 관리 도구, DNS 서버 ...

--dns 정보 확인
PS C:\Users\Administrator> Get-Service dns

Status   Name               DisplayName
------   ----               -----------
Running  dns                DNS Server

--중지
PS C:\Users\Administrator> Stop-Service dns
PS C:\Users\Administrator> Get-Service dns

Status   Name               DisplayName
------   ----               -----------
Stopped  dns                DNS Server

--시작
PS C:\Users\Administrator> Start-Service dns
PS C:\Users\Administrator> Get-Service dns

Status   Name               DisplayName
------   ----               -----------
Running  dns                DNS Server
--zone 생성
PS C:\Users\Administrator> Add-DnsServerPrimaryZone -Name "jiwon.kh" -Zonefile "jiwon.kh.dns"

--A record 추가
PS C:\Users\Administrator> Add-DnsServerResourceRecordA -Name "www" -ZoneName "jiwon.kh" -IpAddress "200.200.200.254" -TimeToLive 00:30:00

생성 확인

--window를 node로
--openssh
PS C:\Users\Administrator> Get-WindowsCapability -Name openssh.server* -online


Name         : OpenSSH.Server~~~~0.0.1.0
State        : NotPresent				#설치 안됨
DisplayName  : OpenSSH 서버
Description  : 안전한 키 관리 및 원격 컴퓨터로부터의 액세스를 위한 OpenSSH 기반 Secure Shell(SSH) 서버입니다.
DownloadSize : 1405120
InstallSize  : 5439396

--openssh 설치
PS C:\Users\Administrator> Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0


Path          :
Online        : True		#설치됨
RestartNeeded : False



PS C:\Users\Administrator> Get-WindowsCapability -Name openssh.server* -online


Name         : OpenSSH.Server~~~~0.0.1.0
State        : Installed				#설치됨
DisplayName  : OpenSSH 서버
Description  : 안전한 키 관리 및 원격 컴퓨터로부터의 액세스를 위한 OpenSSH 기반 Secure Shell(SSH) 서버입니다.
DownloadSize : 1405120
InstallSize  : 5439396

--중지 상태 이므로
PS C:\Users\Administrator> Get-Service sshd

Status   Name               DisplayName
------   ----               -----------
Stopped  sshd               OpenSSH SSH Server

--시작
PS C:\Users\Administrator> Start-Service sshd
PS C:\Users\Administrator> Get-Service sshd

Status   Name               DisplayName
------   ----               -----------
Running  sshd               OpenSSH SSH Server


PS C:\Users\Administrator>
--sshd server 자동으로
PS C:\Users\Administrator> sc.exe config sshd start= auto
[SC] ChangeServiceConfig 성공

Mobaxterm 접근 테스트

--node 등록
--ansible server
[root@ansible-server ~]# vi /etc/ansible/hosts 
[win]
200.200.200.149

[win:vars]
ansible_user=Administrator
ansible_password=				#password 없이 접속하도록 공백
ansible_connection=ssh
ansible_shell_type=powershell
ansible_ssh_common_args=-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null
ansible_ssh_retries=3
ansible_become_method=runas

--2022-00
--ssh 쓸 때 default를 powershell로
PS C:\Users\Administrator> New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force


DefaultShell : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSChildName  : OpenSSH
PSDrive      : HKLM
PSProvider   : Microsoft.PowerShell.Core\Registry
--2022
PS C:\Users\Administrator> mkdir c:\users\Administrator\.ssh


    디렉터리: C:\users\Administrator


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----      2024-03-25  오후 10:50                .ssh
--ansible server
[root@ansible-server ~]# ls -a
.   .ansible       .bash_logout   .bashrc  .config  .lesshst  .ssh     .viminfo                 anaconda-ks.cfg               ansible-playbook-test-02.yml  index.html  test.txt  다운로드  바탕화면  사진  음악
..  .bash_history  .bash_profile  .cache   .cshrc   .local    .tcshrc  Rockylinux-practice.yml  ansible-playbook-systemd.yml  c_inven.lst                   nginx.yml   공개      문서      비디오    서식
[root@ansible-server ~]# cd ./.ssh
[root@ansible-server .ssh]# ls
id_rsa  id_rsa.pub  known_hosts
--directory 없어서 안만들어짐
[root@ansible-server .ssh]# scp ./id_rsa.pub administrator@200.200.200.149:.ssh/authorized_keys
The authenticity of host '200.200.200.149 (200.200.200.149)' can't be established.
ED25519 key fingerprint is SHA256:NzdxMIFbZZ4tyBcMIRyGRsfG4cT31ZHkRjPObj7Mk7s.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '200.200.200.149' (ED25519) to the list of known hosts.
administrator@200.200.200.149's password: 
dest open(".ssh/authorized_keys"): No such file or directory
failed to upload file ./id_rsa.pub to .ssh/authorized_keys
--directory 생성 후 다시 
[root@ansible-server .ssh]# scp ./id_rsa.pub administrator@200.200.200.149:.ssh/authorized_keys
administrator@200.200.200.149's password: 
id_rsa.pub
--2022 key 생성 확인
PS C:\Users\Administrator> Test-Path -Path "C:\Users\Administrator\.ssh\authorized_keys"
True

sshd 설정 파일

--sshd_config
--주석 해제
#PubkeyAuthentication yes
PubkeyAuthentication yes
--주석처리
#Match Group administrators
#       AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

--서비스재시작
PS C:\Users\Administrator> Restart-Service sshd
--접속
[root@ansible-server .ssh]# ssh administrator@200.200.200.149

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

새로운 기능 및 개선 사항에 대 한 최신 PowerShell을 설치 하세요! https://aka.ms/PSWindows

PS C:\Users\Administrator> exit
Connection to 200.200.200.149 closed.

win 설정 종료

--ad-hoc test
--연결 확인
[root@ansible-server ~]# ansible win -m win_ping
200.200.200.149 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

--win 정보 확인
[root@ansible-server ~]# ansible win -m setup
200.200.200.149 | SUCCESS => {
    "ansible_facts": {
        "ansible_architecture": "64비트",
        "ansible_architecture2": "x86_64",
        "ansible_bios_date": "11-12-2020",
        "ansible_bios_version": "6.00",
        "ansible_date_time": {
            "date": "2024-03-25",
--playbook test
[root@ansible-server ~]# echo hi > /root/a.txt
PS C:\Users\Administrator> mkdir c:\temp


    디렉터리: C:\


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----      2024-03-26  오전 12:08                temp

[root@ansible-server ~]# vi /root/copy-local-remote.yml
---
- hosts: win
  gather_facts: no
  tasks:
  - name: Copy a local file to remote
    win_copy:
      src: /root/a.txt
      dest: c:\temp\renamed-a.txt
      
[root@ansible-server ~]# ansible-playbook copy-local-remote.yml 

PLAY [win] **********************************************************************************************************************************************************************************************************************************

TASK [Copy a local file to remote] **********************************************************************************************************************************************************************************************************
changed: [200.200.200.149]

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
200.200.200.149            : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

--2022 파일 생성 확인
PS C:\Users\Administrator> Test-Path -Path "C:\temp\renamed-a.txt"
True
---
- hosts: win
  gather_facts: no
  tasks:
  - name: Copy a local remote to remote
    win_copy:
      src: c:\Windows\system32\drivers\etc\hosts
      dest: c:\temp\hosts_backup
      remote_src: yes
      
[root@ansible-server ~]# ansible-playbook copy-local-remote.yml 

PLAY [win] **********************************************************************************************************************************************************************************************************************************

TASK [Copy a local remote to remote] ********************************************************************************************************************************************************************************************************
changed: [200.200.200.149]

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
200.200.200.149            : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
컴퓨터관리
compmgmt.msc
--사용자 생성하기
--ansible server
[root@ansible-server ~]# vi add-user.yml
---
- hosts: win
  gather_facts: no
  tasks:
    - name: create local group
      win_group:
        name: LocalGroup
        description: LocalUserGroup

    - name: create new users
      win_user:
        name: '{{ item.name }}'
        password: '{{ item.password }}'
        groups:
          - LocalGroup
          - "Remote Desktop Users"
        password_never_expires: yes
      loop:
        - name: User1
          password: Password1
        - name: User2
          password: Password2
          
--실행 확인
[root@ansible-server ~]# ansible-playbook -i /etc/ansible/hosts add-user.yml 

PLAY [win] **********************************************************************************************************************************************************************************************************************************

TASK [create local group] *******************************************************************************************************************************************************************************************************************
changed: [200.200.200.149]

TASK [create new users] *********************************************************************************************************************************************************************************************************************
changed: [200.200.200.149] => (item={'name': 'User1', 'password': 'Password1'})
changed: [200.200.200.149] => (item={'name': 'User2', 'password': 'Password2'})

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
200.200.200.149            : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
--win
PS C:\Users\Administrator> Get-LocalGroupMember -Group "LocalGroup"

ObjectClass Name           PrincipalSource
----------- ----           ---------------
사용자      JIWON-00\User1 Local
사용자      JIWON-00\User2 Local


PS C:\Users\Administrator> Get-LocalGroupMember -Group "Remote Desktop Users"

ObjectClass Name           PrincipalSource
----------- ----           ---------------
사용자      JIWON-00\User1 Local
사용자      JIWON-00\User2 Local
--IIs 설치하기
[root@ansible-server ~]# vi add-iis.yml
---
- hosts: win
  gather_facts: no
  tasks:
  - name: Install IIS Web-Server with sub features and management tools
    win_feature:
      name: Web-Server
      state: present
      include_sub_features: yes
      include_management_tools: yes
    register: win_feature

  - name: Reboot if installing Web-server feature requires it
    win_reboot:
    when: win_feature.reboot_required
    
[root@ansible-server ~]# ansible-playbook -i /etc/ansible/hosts add-iis.yml 

PLAY [win] *********************************************************************************************************

TASK [Install IIS Web-Server with sub features and management tools] ***********************************************
changed: [200.200.200.149]

TASK [Reboot if installing Web-server feature requires it] *********************************************************
skipping: [200.200.200.149]

PLAY RECAP *********************************************************************************************************
200.200.200.149            : ok=1    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
--win
PS C:\Users\Administrator> Get-Service W3SVC

Status   Name               DisplayName
------   ----               -----------
Running  W3SVC              World Wide Web Publishing 서비스

--or
PS C:\Users\Administrator> Get-WindowsFeature -Name Web-Server
>>

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] 웹 서버(IIS)                                        Web-Server                     Installed
--iis 서비스 중지
[root@ansible-server ~]# vi stop-service.yml
- hosts: win
  gather_facts: no
  tasks:
  - name: stop a service
    win_service:
      name: W3SVC
      state: stopped
[root@ansible-server ~]# ansible-playbook stop-service.yml 

PLAY [win] *********************************************************************************************************

TASK [stop a service] **********************************************************************************************
changed: [200.200.200.149]

PLAY RECAP *********************************************************************************************************
200.200.200.149            : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

--win
PS C:\Users\Administrator> Get-Service W3SVC

Status   Name               DisplayName
------   ----               -----------
Stopped  W3SVC              World Wide Web Publishing 서비스

 

'IaC Application > ansible' 카테고리의 다른 글

vyos  (0) 2024.03.27
ansible playbook -  (0) 2024.03.26
ansible ad-hoc  (0) 2024.03.25