피드 구독

With Ansible, users have the flexibility to accept external input while executing their Ansible playbooks without changing the Ansible playbook content. This can be done via the ability to pass extra variables to an Ansible playbook. This feature is available when using the Ansible CLI or Ansible Tower.

[ Download now: A system administrator's guide to IT automation. ]

Why extra variables?

Why should I pass variables to an Ansible playbook when I can declare every variable and value in the playbook or in variable files? This was a recent question I received last time I explained the concept of using extra vars option in Ansible.

The answer lies becomes explicit when you run into scenarios such as the following:

  • What will you do when you want to change the value of a variable? Edit the playbook or variable file?
  • What will you do when you want to use different values for a variable each time you run the Ansible playbook?
  • What will you do when you want to use values for some variables only when running the playbook?

While these questions only scratch the surface, it becomes clear that when you are looking for flexibility, the Ansible extra variable feature is the best answer for most of these solutions. The following use cases explain how you can use extra variables to add flexibility to your Ansible playbooks.

Hard-coding hosts is a bad idea

For example, you create an Ansible playbook that runs on a specific set of hosts and sets those hosts to a group labeled: webgroup. As you complete your Ansible playbook testing, you enable it for production use.

Unfortunately, the operations team or engineers need to run this playbook on a different group of hosts called appgroup. By explicitly hard-coding the hosts group name within the Ansible playbook, you've limited its flexibility requiring changes in the Ansible playbook itself.

What is a better method to solve this issue?

The use of the --extra-vars parameter and modifying the Ansible playbook to take a variable (e.g., nodes) when declaring your hosts. The following example illustrates it:

- hosts: "{{ nodes }}"
  vars_files:
    - vars/main.yml
  roles:
    - { role: geerlingguy.apache }

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. 

# ansible-playbook myplaybook.yaml --extra-vars "nodes=webgroup”

## Or

# ansible-playbook myplaybook.yaml --extra-vars "nodes=appgroup”

This ensures you avoid accidental running of the playbook against hardcoded hosts. If the Ansible playbook fails to specify the hosts while running, Ansible will throw an error and stop, saying no value for nodes.

[ Learn more: Ansible vs. Terraform, clarified ]

Controlling your variables from outside of Ansible roles

Ansible roles are a collection of templates, files, variables, modules, handlers, and tasks created for the purpose of simplifying the reuse of Ansible code.

Within an Ansible role directory structure, you'll have two types of variables inside the following directories:

  • defaults/main.yml - contains variables for a role that can be customized based on the desired usage of the role.
  • vars/main.yml - contains variables for a role that are not intended to be modified.

* Due to --extra-vars having higher precedence than vars/main.yml variables can be modified using the --extra-vars parameter. Modifiable variables should reside in defaults/main.yml

You can set the variable values by using --extra-vars.

For example, using a different port in an Apache installation like below (assuming variables are defined within the defaults/main.yml):

# ansible-playbook deploy-apache.yaml --extra-vars “apache_listen_port=8080”

If you have multiple values to pass, then try this:

# ansible-playbook deploy-apache.yaml --extra-vars “apache_listen_port=8080 apache_listen_port_ssl=443”

How to pass variables containing spaces?

You need to add quotation marks to string values with spaces to pass them as extra variables:

# ansible-playbook deploy-apache.yaml --extra-vars "apache_ssl_protocol='All -SSLv2 -SSLv3'"

Wrap up

[ Need more on Ansible? Take a free technical overview course from Red Hat. Ansible Essentials: Simplicity in Automation Technical Overview. ]

This is just a glimpse of the different options on how to pass variables to an Ansible playbook. For more ways to pass variables to Ansible playbooks, such as using JSON and external variable files, check out the Ansible documentation site.


저자 소개

Gineesh Madapparambath is a Platform & DevOps Consultant at Red Hat Singapore, specializing in automation and containerization with Ansible and OpenShift. 

He has worked as a Systems Engineer, Automation Specialist, and content author. His primary focus is on Ansible Automation, Containerization (OpenShift and Kubernetes), and Infrastructure as Code (Terraform). He is the author of the book "Ansible for Real-Life Automation".

 

Read full bio
UI_Icon-Red_Hat-Close-A-Black-RGB

채널별 검색

automation icon

오토메이션

기술, 팀, 인프라를 위한 IT 자동화 최신 동향

AI icon

인공지능

고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트

open hybrid cloud icon

오픈 하이브리드 클라우드

하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요

security icon

보안

환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보

edge icon

엣지 컴퓨팅

엣지에서의 운영을 단순화하는 플랫폼 업데이트

Infrastructure icon

인프라

세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보

application development icon

애플리케이션

복잡한 애플리케이션에 대한 솔루션 더 보기

Original series icon

오리지널 쇼

엔터프라이즈 기술 분야의 제작자와 리더가 전하는 흥미로운 스토리