ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ansible variables
    ansible 2022. 2. 6. 15:43

    inventory 에 정의하기

    inventory.txt

    web1 ansible_host=192.168.0.17
    
    [web_servers]
    web1
    
    [web_servers:vars]
    SERVICE_PORT=8080
    
    [all:vars]
    HOME_DIR='/home'

    playbook.yml

    - name: inventory variables
      hosts: web_servers
      tasks:
        - name: echo vars
          command: echo 'HOME_DIR={{ HOME_DIR }} SERVICE_PORT={{ SERVICE_PORT }}'
          register: result
    
        - name: echo result
          debug: msg={{ result['stdout_lines'] }}

    playbook 에 정의하기

    playbook 내에서 vars, vars_files 로 variable 을 정의할 수 있다.

    var.yml

    common:
      HOME_DIR: '/home'

    playbook.yml

    - name: inventory variables
      hosts: web_servers
      vars_files:
        - var.yml
      vars:
        SERVICE_PORT: 8080
      tasks:
        - name: my test
          command: echo 'HOME_DIR={{ common.HOME_DIR }} SERVICE_PORT={{ SERVICE_PORT }}'
          register: result
    
        - name: echo result
          debug: msg={{ result['stdout_lines'] }}

    실행시 variable 변경하기

    --extra-vars (or -e) 사용해 변경 가능

    ansible-playbook -i inventory.txt -e 'HOME_DIR=/user SERVICE_PORT=9090' playbook.yml

    주의 사항

    아래처럼 jinja2 로 variable(ECHO_COMMAND) 이 바로 참조될 경우 따옴표로 감싸줘야 한다.

    ERROR OK
    - name: inventory variables
      hosts: web_servers
      tasks:
        - name: my test
          command: {{ ECHO_COMMAND }}
    - name: inventory variables
      hosts: web_servers
      tasks:
        - name: my test
          command: '{{ ECHO_COMMAND }}'

     

    참고: https://www.udemy.com/course/learn-ansible/

    'ansible' 카테고리의 다른 글

    ansible loops  (0) 2022.02.06
    ansible conditionals  (0) 2022.02.06
    ansible modules  (0) 2022.02.06
    ansible playbooks  (0) 2022.02.06
    ansible inventory  (0) 2022.02.05

    댓글

Designed by Tistory.