Ansible - 在变量查找中使用字符串

时间:2016-05-20 12:42:53

标签: ansible ansible-playbook

我正在努力让我的剧本了解他们的环境;那是生产还是阶段。

我的剧本首先成功地为其环境拉取ec2_tag并设置为变量'env'。在ec2配置任务中,我想在vpc和子网查找中使用'env'变量,因此它根据其环境抓取正确的变量。下面我尝试将'env'变量添加到查找中,但我得到一个完整的字符串,而不是从我的变量文件中提取它。

我是否需要在{{}}

中添加一些逻辑检查
- name: Provision instance
      ec2:
        key_name: "{{ aws_public_key }}"
        instance_type: t2.medium
        image: "{{ aws_ubuntu_ami }}"
        wait: true
        vpc_subnet_id: "{{ env + '_subnet_public1' }}"
        group_id: "{{ env + '_app_group' }}"
        assign_public_ip: yes
        instance_tags:
          Name: "{{ sys_name }}"
          Environment: "{{ env }}"
        region: "{{ aws_region }}"
        volumes:
          - device_name: /dev/sda1
            volume_size: 300
            delete_on_termination: true
      register: ec2

1 个答案:

答案 0 :(得分:1)

如果您想进行变量插值,则需要使用hostvars[inventory_hostname]['variable'] syntax

FAQs简要介绍了这一点,但对于您的用例,您应该可以执行以下操作:

- name: Provision instance
      ec2:
        key_name: "{{ aws_public_key }}"
        instance_type: t2.medium
        image: "{{ aws_ubuntu_ami }}"
        wait: true
        vpc_subnet_id: hostvars[inventory_hostname][env + '_subnet_public1']
        group_id: hostvars[inventory_hostname][env + '_app_group']
        assign_public_ip: yes
        instance_tags:
          Name: "{{ sys_name }}"
          Environment: "{{ env }}"
        region: "{{ aws_region }}"
        volumes:
          - device_name: /dev/sda1
            volume_size: 300
            delete_on_termination: true
      register: ec2