code

명령 줄에서 Ansible 플레이 북의 호스트 변수 재정의

codestyles 2020. 9. 18. 08:14
반응형

명령 줄에서 Ansible 플레이 북의 호스트 변수 재정의


다음은 내가 사용중인 플레이 북의 일부입니다 ( server.yml).

- name: Determine Remote User
  hosts: web
  gather_facts: false
  roles:
    - { role: remote-user, tags: [remote-user, always] }

내 호스트 파일에는 다른 서버 그룹이 있습니다. 예 :

[web]
x.x.x.x

[droplets]
x.x.x.x

지금은 실행할 ansible-playbook -i hosts/<env> server.yml및 오버라이드 (override) hosts: web에서 server.yml이 작전을 실행합니다 [droplets].

server.yml직접 편집하지 않고 일회성으로 재정의 할 수 있습니까 ?

감사.


Ansible이이 기능을 제공한다고 생각하지 않습니다. 수행 할 수있는 작업은 다음과 같습니다.

hosts: "{{ variable_host | default('web') }}"

variable_host명령 줄 또는 vars 파일에서 전달할 수 있습니다 . 예 :

ansible-playbook server.yml --extra-vars "variable_host=newtarget(s)"

솔루션을 찾고 계신 분들께.
플레이 북

- hosts: '{{ host }}'
  tasks:
  - debug: msg="Host is {{ ansible_fqdn }}"

목록

[web]
x.x.x.x

[droplets]
x.x.x.x

명령 : ansible-playbook deplyment.yml -i hosts --extra-vars "host=droplets" 따라서 extra-vars에 그룹 이름을 지정할 수 있습니다.


이것은 약간 늦었지만 --limit or -l명령을 사용 하여 패턴을보다 구체적인 호스트로 제한 할 수 있다고 생각 합니다. (버전 2.3.2.0)

당신은 가질 수 있습니다 - hosts: all (or group) tasks: - some_task

그런 다음 플래그를 ansible-playbook playbook.yml -l some_more_strict_host_or_pattern사용 --list-hosts하여이 구성이 적용되는 호스트를 확인합니다.


인벤토리가 필요하지 않고 다음과 같은 간단한 명령으로 작동하는 다른 접근 방식을 사용하고 있습니다.

ansible-playbook site.yml -e working_host=myhost

이를 수행하려면 두 가지 연극이있는 플레이 북이 필요합니다.

  • 첫 번째 재생은 localhost에서 실행되고 메모리 인벤토리의 알려진 그룹에 호스트 (주어진 변수에서)를 추가합니다.
  • 이 알려진 그룹에서 두 번째 플레이가 실행됩니다.

작업 예제 (복사하고 이전 명령으로 실행) :

- hosts: localhost
  connection: local
  tasks:
  - add_host:
      name: "{{ working_host }}"
      groups: working_group
    changed_when: false

- hosts: working_group
  gather_facts: false
  tasks:
  - debug:
      msg: "I'm on {{ ansible_host }}"

ansible 2.4.3 및 2.3.3을 사용하고 있습니다.


I changed mine to default to no host and have a check to catch it. That way the user or cron is forced to provide a single host or group etc. I like the logic from the comment from @wallydrag. The empty_group contains no hosts in the inventory.

- hosts: "{{ variable_host | default('empty_group') }}"

Then add the check in tasks:

   tasks:
   - name: Fail script if required variable_host parameter is missing
     fail:
       msg: "You have to add the --extra-vars='variable_host='"
     when: (variable_host is not defined) or (variable_host == "")

We use a simple fail task to force the user to specify the Ansible limit option, so that we don't execute on all hosts by default/accident.

The easiest way I found is this:

---
- name: Force limit
  # 'all' is okay here, because the fail task will force the user to specify a limit on the command line, using -l or --limit
  hosts: 'all'

  tasks:
  - name: checking limit arg
    fail:
      msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
    when: ansible_limit is not defined
    run_once: true

Now we must use the -l (= --limit option) when we run the playbook, e.g.

ansible-playbook playbook.yml -l www.example.com

Limit option docs:

Limit to one or more hosts This is required when one wants to run a playbook against a host group, but only against one or more members of that group.

Limit to one host

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1"

Limit to multiple hosts

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1,host2"

Negated limit.
NOTE: Single quotes MUST be used to prevent bash interpolation.

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'all:!host1'

Limit to host group

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'group1'


If you want to run a task that's associated with a host, but on different host, you should try delegate_to.

In your case, you should delegate to your localhost (ansible master) and calling ansible-playbook command


Just came across this googling for a solution. Actually, there is one in Ansible 2.5. You can specify your inventory file with --inventory, like this: ansible --inventory configs/hosts --list-hosts all


I am using ansible 2.5 (2.5.3 exactly), and it seems that the vars file is loaded before the hosts param is executed. So you can set the host in a vars.yml file and just write hosts: {{ host_var }} in your playbook

For example, in my playbook.yml:

---
- hosts: "{{ host_name }}"
  become: yes
  vars_files:
    - vars/project.yml
  tasks:
    ... 

And inside vars/project.yml:

---

# general
host_name: your-fancy-host-name

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}}"

참고URL : https://stackoverflow.com/questions/33222641/override-hosts-variable-of-ansible-playbook-from-the-command-line

반응형