另一个变量的可变值ansible

时间:2019-06-26 23:42:37

标签: ansible

很抱歉,如果变量中有很多关于变量的帖子,我的用例是不同的。  尝试根据当前主机的索引号从变量列表“ efs_list”访问元素。库存中有三台主机

  vars:
    efs_list:
      - efs1
      - efs2
      - efs3
    sdb_index: "{{ groups['all'].index(inventory_hostname) }}" 

值应如下   host1- efs1   主机2- efs2   host3- efs3

试图通过efs_list访问它。{{sdb_index}} 对于- debug: var=efs_list.{{ sdb_index }},输出符合预期

ok: [10.251.0.174] => {
    "efs_list.0": "efs1"
}
ok: [10.251.0.207] => {
    "efs_list.1": "efs2"
}
ok: [10.251.0.151] => {
    "efs_list.2": "efs3"
}

但是

     - debug:
        msg: "{{ efs_list.{{ sdb_index }} }}"

fatal: [10.251.0.174]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ efs_list.{{ sdb_index }} }}"}

---
- name: SDB Snapshots Creation
  hosts: all
  remote_user: "centos"
  become: yes
  vars:
    efs_list:
      - efs1
      - efs2
      - efs3
    sdb_index: "{{ groups['all'].index(inventory_hostname) }}" 

  tasks:
    - debug: var=efs_list.{{ sdb_index }}

    - debug:
        msg:  "{{ efs_list.{{ sdb_index }} }}"

    - name: Get  Filesystem ID
      become: false
      local_action: command aws efs describe-file-systems --creation-token "{{ efs_list.{{ sdb_index }} }}"
         --region us-east-1 --query FileSystems[*].FileSystemId --output text  
      register: fs_id

应将列表元素归因于当前索引enter code here

1 个答案:

答案 0 :(得分:0)

extract过滤器将完成此工作。过滤器的输入必须是索引列表和容器(在这种情况下为数组)。以下任务

- set_fact:
    sdb_index: "{{ [] + [ groups['all'].index(inventory_hostname) ] }}"
- debug:
    msg: "{{ sdb_index|map('extract', efs_list)|list }}"

给予

ok: [host1] => {
    "msg": [
        "efs1"
    ]
}
ok: [host2] => {
    "msg": [
        "efs2"
    ]
}
ok: [host3] => {
    "msg": [
        "efs3"
    ]
}

如果主机未在清单中排序,则有必要在游戏中对其进行排序

- set_fact:
    my_hosts: "{{ groups['all']|sort }}"
- set_fact:
    sdb_index: "{{ [] + [ my_hosts.index(inventory_hostname) ] }}"
- debug:
    msg: "{{ sdb_index|map('extract', efs_list)|list }}"