IaC(Infrastructure as Code)

Ansible Part. 5 (Variables)

cwchoiit 2024. 3. 18. 11:37
728x90
반응형
SMALL
728x90
SMALL

 

Variables

Ansible에서 변수를 사용하는 방법은 다양하다. 그 중 몇가지를 알아보는 시간을 가져보자.

 

inventory 파일

다음과 같이 inventory 파일을 작성해보자. ubuntu 그룹에 원하는 변수를 아래처럼 이어 작성하면 된다.

[amazon]
amazon1 ansible_host=43.202.58.98 ansible_user=ec2-user 
amazon2 ansible_host=3.38.182.30 ansible_user=ec2-user

[ubuntu]
ubuntu1 ansible_host=ec2-43-201-253-181.ap-northeast-2.compute.amazonaws.com ansible_user=ubuntu user_name=cwchoiit user_comment="From inventory" user_shell=/bin/bash user_uid=7777
ubuntu2 ansible_host=ec2-3-38-192-32.ap-northeast-2.compute.amazonaws.com ansible_user=ubuntu user_name=cwchoiit user_comment="From inventory" user_shell=/bin/bash user_uid=7777

[linux:children]
amazon
ubuntu

 

이 상태로 다음 playbook을 실행해보자. 참고로 Ansible에서 변수를 사용하려면 "{{}}" 이렇게 사용하면 된다.

- name: Playbook
  hosts: ubuntu
  become: true
  tasks:
    - name: "Create a user"
      user:
        name: "{{ user_name }}"
        comment: "{{ user_comment }}"
        shell: "{{ user_shell }}"
        uid: "{{ user_uid }}"

 

ansible-playbook -i with-var.inv playbook.yaml

실행이 정상적으로 됐으면 해당 리모트 호스트에 SSH를 통해 들어가보자. 들어오면 다음 명령어를 수행

cat /etc/passwd

그럼 최하단에 다음 사용자가 추가됐음을 확인할 수 있다.

 

Playbook 내 선언

이번에는 playbook 파일 내에 선언하는 방법이다. 다음과 같이 vars라는 키에 하나씩 넣어줄 수 있다.

- name: Playbook
  hosts: ubuntu
  become: true
  vars:
    user_name: "cwchoiit"
    user_comment: "from playbook vars"
    user_shell: /bin/bash
    user_uid: "7777"
  tasks:
    - name: "Create a user"
      user:
        name: "{{ user_name }}"
        comment: "{{ user_comment }}"
        shell: "{{ user_shell }}"
        uid: "{{ user_uid }}"

 

이 상태로 playbook을 실행해보자. 물론 여기서는 inventory 파일에 선언한 변수는 지워야한다. 실행한 후 리모트 호스트에 들어가서 다시 확인해보면 다음과 같은 결과를 볼 수 있다.

 

Playbook 내 파일 경로 선언

이번엔 playbook 파일 내 선언을 따로 변수를 선언한 파일 경로로 하는 방법이다.

vars.yaml

user_name: "cwchoiit"
user_comment: "from vars.yaml file"
user_shell: "/bin/bash"
user_uid: "7777"

playbook.yaml

- name: Playbook
  hosts: ubuntu
  become: true
  vars_files:
    - vars.yaml
  tasks:
    - name: "Create a user"
      user:
        name: "{{ user_name }}"
        comment: "{{ user_comment }}"
        shell: "{{ user_shell }}"
        uid: "{{ user_uid }}"

 

이 상태로 playbook을 실행해보자. 물론 여기서도 마찬가지로 inventory 파일에 선언한 변수는 지워야한다. 실행한 후 리모트 호스트에 들어가서 다시 확인해보면 다음과 같은 결과를 볼 수 있다.

 

Playbook 실행 명령어에 변수 지정

이번엔 실행하는 명령어에 변수를 추가하는 방법이다.

실행 후 리모트 호스트에 들어가서 확인해보자. 다음과 같은 결과를 볼 수 있다.

 

근데, 이렇게 쭉 나열하기는 명령어가 너무 길어져서 지저분하다면 다음과 같이 변수 파일 경로를 변수로 줄 수도 있다.

 

728x90
반응형
LIST

'IaC(Infrastructure as Code)' 카테고리의 다른 글

Ansible Part. 7 (Condition)  (0) 2024.03.18
Ansible Part. 6 (Loop)  (0) 2024.03.18
Ansible Part. 4 (Handler)  (0) 2024.03.18
Ansible Part. 3 (Playbook)  (0) 2024.03.18
Ansible Part. 2 (Adhoc)  (3) 2024.03.17