인프라/Ansible

Infra IT 자동화 Tool - 앤서블(Ansible) 문법

snowman95 2021. 5. 25. 20:32
728x90
반응형

 


문법

□ 변수 정의 (vars)

tasks 섹션 전에 vars 섹션으로 변수를 정의

vars:
  hello: Hello
tasks:
  - name: Hello World
    debug: msg=“{{ hello }} Ansible”

 

□ 조건 분기 실행 (when)

tasks에서 모듈명 다음 줄에 when 을 기술하여 모듈의 실행 조건을 정의

vars:
  hello: Hello
tasks:
  - name: Hello World
    debug: msg=“{{ hello }} Ansible”

 

□ 루프 실행 (Loops)

tasks에서 모듈명 다음 줄에 with_변수명 기술하고, module에서 {{ 변수명 }} 로 사용

with_items
with_nested
with_dict
with_indexed_items
with_ini
with_flattened
with_file
...
name: add users
user: name={{ item }} state=present groups=user
with_items:
- open
- naru
- admin


 Include

- include: test/main.yml

 

 Ad-hoc Task 실행

$ ansible <host-pattern> [options]

$ ansible 192.168.11.3 -m ping -u root --ask-pass
SSH password:
192.168.23.14 | success >> {
"changed": false,
"ping": "pong"
}

$ ansible web01.opennaru.com -m command -a ‘/sbin
/reboot’ --ask-pass

 

□ 템플릿

  • YAML 파일 뿐만 아니라 모든 파일에서 활용 가능함
  • 일반적으로 파일 확장명을 .j2로 함
    ex) index.php.j2
  • Template task 일 때 jinja2가 적용 가능 (copy task는 적용 안됨)
    Jinja2 Template 엔진임 (웹 프레임워크인 FLASK기본내장되어 많이 사용됨)
     {{ ... }} : 변수나 표현식
     {% ... %} : iffor같은 제어문
     {# ... #} : 주석
    tasks:
      - name: deploy my.cnf
        template: src=my.cnf.j2 dest=/etc/my.cnf
    
    filename: my.cnf.j2
    [mysqld]
    user = {{ mysql_user }}
    port = {{ mysql_port }}
    datadir = /var/lib/mysql
    socket = /var/lib/mysql/mysql.sock
    pid-file = /var/lib/mysqld/mysqld.pid

 

 

Playbook 작성 예시

예시1. Apache 설치

  • Playbook : apache_setup.yml 

 

  • Inventory : /etc/ansible/hosts
    [apache] web[01:03].ooo.com 192.168.11.3
  • Intall
    $ ansible-playbook apache_setup.yml

 

  • httpd.conf Templates 환경변수

 

 

반응형