When you write an Ansible playbook, you sometimes need to pass data into your play at runtime. To do that, you can use a variable, a sort of placeholder for data that's meant to be determined at some point in the future.
There are lots of places to create variables for your playbooks, such as an inventory file, included files, or even dynamically in your playbook itself. However, you can also pass variables in the terminal when you launch your playbook.
[ Download now: A system administrator's guide to IT automation. ]
Using a variable
To use a variable in a playbook, you reference it in curly braces ({{ }}
). For example, this simple playbook uses the debug
module to print the value of a variable to the terminal:
---
- hosts: localhost
tasks:
- name: echo a variable
debug:
msg: "{{ my_var }}"
Because the variable hasn't been defined, the play results in an error:
$ ansible-playbook ./example.yaml
[...]
fatal: [localhost]: FAILED! =>
{"msg": "The task includes an option with an undefined variable.
The error was: 'my_var' is undefined...
[ Get started with IT automation with the Ansible Automation Platform beginner's guide. ]
To define a variable dynamically when you run a playbook, use the --extra-vars
option along with the key and value of the variable you want to define. In this example, the key is my_var
because that's the string referenced in the playbook, and the value is any string you want the variable to contain.
$ ansible-playbook --extra-vars my_var=foo ./example.yaml
[...]
TASK [echo a variable] ****************************
ok: [localhost] => {
"msg": "foo"
}
PLAY RECAP ****************************************
localhost : ok=2 changed=0 failed=0 [...]
This time, the variable's value is passed into Ansible through the command option and successfully printed to the terminal.
Variables and Ansible
Ansible supports many ways of passing variables into scripts, generating variables within scripts, and even processing variables as part of a playbook's tasks. For more information on how to process variables in a playbook using filters, read 2 practical ways to use filters to manipulate data in Ansible and Network configuration with Ansible filters.
저자 소개
Seth Kenlon is a Linux geek, open source enthusiast, free culture advocate, and tabletop gamer. Between gigs in the film industry and the tech industry (not necessarily exclusive of one another), he likes to design games and hack on code (also not necessarily exclusive of one another).
채널별 검색
오토메이션
기술, 팀, 인프라를 위한 IT 자동화 최신 동향
인공지능
고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트
오픈 하이브리드 클라우드
하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요
보안
환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보
엣지 컴퓨팅
엣지에서의 운영을 단순화하는 플랫폼 업데이트
인프라
세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보
애플리케이션
복잡한 애플리케이션에 대한 솔루션 더 보기
가상화
온프레미스와 클라우드 환경에서 워크로드를 유연하게 운영하기 위한 엔터프라이즈 가상화의 미래