Override hosts variable of Ansible playbook from the command line

前端 未结 11 1761
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 12:29

This is a fragment of a playbook that I\'m using (server.yml):

- name: Determine Remote User
  hosts: web
  gather_facts: false
  roles:
    - {         


        
11条回答
  •  -上瘾入骨i
    2020-12-12 13:19

    Here's a cool solution I came up to safely specify hosts via the --limit option. In this example, the play will end if the playbook was executed without any hosts specified via the --limit option.

    This was tested on Ansible version 2.7.10

    ---
    - name: Playbook will fail if hosts not specified via --limit option.
      # Hosts must be set via limit. 
      hosts: "{{ play_hosts }}"
      connection: local
      gather_facts: false
      tasks:
      - set_fact:
          inventory_hosts: []
      - set_fact:
          inventory_hosts: "{{inventory_hosts + [item]}}"
        with_items: "{{hostvars.keys()|list}}"
    
      - meta: end_play
        when: "(play_hosts|length) == (inventory_hosts|length)"
    
      - debug:
          msg: "About to execute tasks/roles for {{inventory_hostname}}"
    

提交回复
热议问题