클라우드 아카이브

[IaC/앤서블] 앤서블 겔럭시를 이용한 서버 패스워드 변경 자동화(2) 본문

Cloud Native Solution/[IaC] ansible

[IaC/앤서블] 앤서블 겔럭시를 이용한 서버 패스워드 변경 자동화(2)

Cloud Engineer 2021. 8. 22. 16:35

목적

(1)에서 구축한 컨테이너 시스템에서 공식 레퍼런스 및 문서를 바탕으로 OS 패스워드 변경하는 작업을 수행하겠습니다. 그리고 다음 포스팅에서는 본 시리즈를 회고 및 정리해보는 시간을 갖겠습니다.

Linux (RHEL 7)

Bastion 노드에 접속하여 작업 대상 노드에 SSH 통신을 통해 패스워드 변경을 자동화하는 작업을 진행하겠습니다. 레퍼런스에서 다양한 명령어를 검색해가며 시행착오를 하는 과정을 일부 담았으니 이를 생략하실 분은 1. 레퍼런스에서 명령어 찾기 부분을 넘어가시면 됩니다.

1. 레퍼런스에서 명령어 찾기

ansible-docs 명령어를 사용하여 필요한 모듈을 찾아보겠습니다. 먼저 레퍼런스에 구성된 모듈 리스트를 조회해보겠습니다.

[root@23ad9c3616a5 workspace]# ansible-doc --list
a10_server                                             Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' server object                                                                         
a10_server_axapi3                                      Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                                                                                        
a10_service_group                                      Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups                                                                        
a10_virtual_server                                     Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' virtual servers                                                                       
aci_aaa_user                                           Manage AAA users (aaa:User)                                                                                                                   
aci_aaa_user_certificate                               Manage AAA user certificates (aaa:UserCert)                                                                                                   
aci_access_port_block_to_access_port                   Manage port blocks of Fabric interface policy leaf profile interface selectors (infra:HPortS, infra:PortBlk)                                  
aci_access_port_to_interface_policy_leaf_profile       Manage Fabric interface policy leaf profile interface selectors (infra:HPortS, infra:RsAccBaseGrp, infra:PortBlk)                             
aci_access_sub_port_block_to_access_port               Manage sub port blocks of Fabric interface policy leaf profile interface selectors (infra:HPortS, infra:SubPortBlk)                           
aci_aep                                                Manage attachable Access Entity Profile (AEP) objects (infra:AttEntityP, infra:ProvAcc)                                                       
aci_aep_to_domain                                      Bind AEPs to Physical or Virtual Domains (infra:RsDomP) 
...
...

 

뭐가 엄청 많네요.. ㅎㅎ 머리가 아픕니다...
음.. 그럼 OS에서 사용자 계정과 관련된 명령어를 생각해보죠.
패스워드와 관련될 것 같은 명령어를 검색해보겠습니다.
먼저 password를 키워드로 한번 검색해볼까요?

[root@23ad9c3616a5 workspace]# ansible-doc --list | grep password
bigip_password_policy                                  Manages the authentication password policy on a BIG-IP                                                                                        
cs_instance_password_reset                             Allows resetting VM the default passwords on Apache CloudStack based clouds                                                                   
ec2_win_password                                       gets the default administrator password for ec2 windows instances                                                                             
iam_password_policy                                    Update an IAM Password Policy                                                                                                                 
ldap_passwd                                            Set passwords in LDAP                                                                                                                         
netapp_e_auth                                          NetApp E-Series set or update the password for a storage array                                                                                
nxos_vtp_password                                      Manages VTP password configuration                                                                                                            
onepassword_facts                                      Gather items from 1Password and set them as facts                                                                                             
panos_admin                                            Add or modify PAN-OS user accounts password                                                                                                   
panos_admpwd                                           change admin password of PAN-OS device using SSH with SSH key

뭔가 그렇다할 명령어가 나오지 않네요...
그럼 사용자 계정과 관련될 것 같은 account를 키워드로 한번 검색해보겠습니다.

[root@23ad9c3616a5 workspace]# ansible-doc --list | grep account
acme_account                                           Create, modify or delete ACME accounts                                                                                                        
acme_account_info                                      Retrieves information on ACME accounts                                                                                                        
avi_useraccount                                        Avi UserAccount Module                                   
...                              
azure_rm_cosmosdbaccount                               Manage Azure Database Account instance                  
...
gcp_iam_service_account                                Creates a GCP ServiceAccount                                                                                  
...                              
user                                                   Manage user accounts                                     
...
win_user                                               Manages local Windows user accounts

뭔가 많이 나왔지만 우리가 주목할만한 모듈이 나왔습니다!
바로! 아래 두가지 명령어입니다.

user : Manage user accounts
win_user : Manages local Windows user accounts

win_user는 windows에서 OS 사용자 관련 변경 작업을 진행할 때 참고하면 좋을듯 해서 일단 가져왔습니다 ㅎㅎ
본 포스팅에서는 user의 패스워드를 변경하는 것이 목표이므로 user에 대해 레퍼런스 조회를 해보겠습니다.

[root@23ad9c3616a5 workspace]# ansible-doc user
> USER    (/usr/lib/python2.7/site-packages/ansible/modules/system/user.py)

        Manage user accounts and user attributes. For Windows targets, use the [win_user] module instead.

  * This module is maintained by The Ansible Core Team
OPTIONS (= is mandatory):

- append
        If `yes', add the user to the groups specified in `groups'.
        If `no', user will only be added to the groups specified in `groups', removing them from all other groups.
        Mutually exclusive with `local'
        [Default: False]
        type: bool

- authorization
        Sets the authorization of the user.
        Does nothing when used with other platforms.
        Can set multiple authorizations using comma separation.
        To delete all authorizations, use `authorization='''.
        Currently supported on Illumos/Solaris.
        [Default: (null)]
        type: str
        version_added: 2.8

- comment
        Optionally sets the description (aka `GECOS') of user account.
        [Default: (null)]
        type: str
...
EXAMPLES:

- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
  user:
    name: johnd
    comment: John Doe
    uid: 1040
    group: admin

- name: Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups
  user:
    name: james
    shell: /bin/bash
    groups: admins,developers
    append: yes
...

뭐가 많네요..
password와 관련된 무언가를 찾기 위해서 password를 키워드로 찾아보겠습니다.

[root@23ad9c3616a5 workspace]# ansible-doc user | grep password
- password
        Optionally set the user's password to this crypted value.
        See https://docs.ansible.com/ansible/faq.html#how-do-i-generate-encrypted-passwords-for-the-user-module for details on various ways to generate these
        password values.
- password_lock
        Lock the password (usermod -L, pw lock, usermod -C).
        This option does not disable the user, only lock the password. Do not change the password in the same task.
- update_password
        `always' will update passwords if they differ.
        `on_create' will only set the password for newly created users.
password:
  description: Masked value of the password
  returned: When C(state) is 'present' and C(password) is not empty

드디어 찾았습니다! 우리가 user라는 모듈에서 주목할 명령어는 update_password password입니다.

  1. update_password
    1. always will update passwords if they differ.
    2. on_create will only set the password for newly created users.
  2. password
    • description: Masked value of the password
    • returned: When C(state) is 'present' and C(password) is not empty

자 이제 두 명령어를 바탕으로 앤서블 겔릭서를 구성하는 role을 만들어보겠습니다.

2. ansible-galaxy 생성

1. role init

먼저 패스워드 변경이라는 role을 초기화하겠습니다.

# role 초기화
[root@23ad9c3616a5 roles]# ansible-galaxy init 01.change_password

# role을 중앙에서 관리할 yaml 파일 생성
[root@23ad9c3616a5 roles]# touch main.yml
.
|-- 01.change_password
| |-- README.md
| |-- defaults
| | -- main.yml
| |-- files
| |-- handlers
| | -- main.yml
| |-- meta
| | -- main.yml
| |-- tasks
| | -- main.yml
| |-- templates
| |-- tests
| | |-- inventory
| | -- test.yml
| -- vars
| -- main.yml
-- main.yml

2. default, files, meta, templates, tests를 제거

해당 4개 디렉토리는 작업을 하는데 필요없기 때문에 제거하겠습니다.

[root@23ad9c3616a5 roles]# rm -rf default
[root@23ad9c3616a5 roles]# rm -rf files
[root@23ad9c3616a5 roles]# rm -rf meta
[root@23ad9c3616a5 roles]# rm -rf templates
[root@23ad9c3616a5 roles]# rm -rf tests

[작업 디렉토리 구조 최종 상태]

.
|-- 01.change_password
| |-- README.md
| |-- tasks
| | -- main.yml
| -- vars
| -- main.yml
-- main.yml

3. 추상화된 노드를 사용할 중앙 yaml 파일 작성

(1)을 통해 등록한 전체 노드(all)에 대해 01.change_password라는 role을 구동시키도록 작성합니다.

---
- name: change password
  hosts: all
  roles:
    - 01.change_password

4. 사용할 변수 정의

/workspace/roles/01.change_password/vars/main.yaml 파일에 role에서 사용할 변수를 정의하고 값을 할당합니다.

---
# vars file for change_password
my_username: node
my_password: admin123

지금부터 위 변수는 01.change_password을 구성하는 모든 디렉토리에서 사용 가능합니다.

5. task 작성 (Playbook를 떠올리기)

/workspace/roles/01.change_password/tasks/main.yaml 파일에 role에서 이행할 모듈을 작성합니다.

---
# tasks file for change_password
- name: start to change password
  become: true
  user:
    name: "{{ my_username }}"
    update_password: always
    password: "{{ my_password | password_hash('sha512') }}"
    shell: /bin/bash

작성한 모듈을 풀어 설명하면,

  1. my_username이라는 변수에 지정한 값을 name으로 갖는 account를 탐색
  2. 만약 기존 패스워드와 my_password의 변수값과 다르다면, my_password 값으로 패스워드를 변경
  3. 패스워드를 암호화하는 해싱 알고리즘은 sha512로 설정
  4. bash 쉘을 통해 명령어를 수행

6. 명령어 실행 결과

[root@23ad9c3616a5 roles]# ansible-playbook main.yml -k
SSH password: 

PLAY [change password] ***********************************************************************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************************************************************************
ok: [172.18.0.3]
ok: [172.18.0.4]

TASK [01.change_password : start to change password] *****************************************************************************************************************************************************
changed: [172.18.0.3]
changed: [172.18.0.4]

PLAY RECAP ***********************************************************************************************************************************************************************************************
172.18.0.3                 : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
172.18.0.4                 : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

명령어가 정상적으로 작동했음을 알 수 있습니다. 작업 대상 노드에 정상적으로 반영됬는지 직접 확인하고 싶으시면 해당 노드에 접속해서 passwd 명령어를 이용하여 태스트를 하시면 됩니다.

마무리

ansible의 레퍼런스를 이용하여 패스워드 변경 작업을 진행하는 포스팅을 진행했습니다. IT 엔지니어는 되면 끝나는 것이 아닌, "레퍼런스를 기반으로 문제 해결에 도움을 주는 도구의 사용법을 빠르게 익혀 적용"할 수 있어야한다고 생각합니다. 따라서 본 포스팅을 작성하게 되었습니다. 포스팅을 읽어주셔서 감사합니다.

Comments