Sharing ansible variable between plays The 2019 Stack Overflow Developer Survey Results Are In Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Come Celebrate our 10 Year Anniversary!Setting dynamic inventory hostnames from AnsibleAnsible: How to access hostvars in task?Ansible: setting hostname over inventoryAnsible EC2 Hosts Script Missing InstanceAnsible fact from another hostAnsible: Share inventory variable between groupsAnsible | Access multi dimensional variable for when conditional in nested loop taskUsing Ansible ini_file with nested dict?Calling Ansible hostvars group variable at later point in playAnsible: Loop over registered output in the next taskSetting dynamic inventory hostnames from Ansible

Multi tool use
Multi tool use

What is the padding with red substance inside of steak packaging?

How do I design a circuit to convert a 100 mV and 50 Hz sine wave to a square wave?

how can a perfect fourth interval be considered either consonant or dissonant?

should truth entail possible truth

Is an up-to-date browser secure on an out-of-date OS?

Working through the single responsibility principle (SRP) in Python when calls are expensive

Are there continuous functions who are the same in an interval but differ in at least one other point?

"... to apply for a visa" or "... and applied for a visa"?

Would an alien lifeform be able to achieve space travel if lacking in vision?

Can withdrawing asylum be illegal?

Why not take a picture of a closer black hole?

What was the last x86 CPU that did not have the x87 floating-point unit built in?

Was credit for the black hole image misappropriated?

What aspect of planet Earth must be changed to prevent the industrial revolution?

Am I ethically obligated to go into work on an off day if the reason is sudden?

Does Parliament need to approve the new Brexit delay to 31 October 2019?

Variable with quotation marks "$()"

Do warforged have souls?

Do I have Disadvantage attacking with an off-hand weapon?

Simulating Exploding Dice

Why don't hard Brexiteers insist on a hard border to prevent illegal immigration after Brexit?

How to determine omitted units in a publication

Are spiders unable to hurt humans, especially very small spiders?

Sort list of array linked objects by keys and values



Sharing ansible variable between plays



The 2019 Stack Overflow Developer Survey Results Are In
Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Come Celebrate our 10 Year Anniversary!Setting dynamic inventory hostnames from AnsibleAnsible: How to access hostvars in task?Ansible: setting hostname over inventoryAnsible EC2 Hosts Script Missing InstanceAnsible fact from another hostAnsible: Share inventory variable between groupsAnsible | Access multi dimensional variable for when conditional in nested loop taskUsing Ansible ini_file with nested dict?Calling Ansible hostvars group variable at later point in playAnsible: Loop over registered output in the next taskSetting dynamic inventory hostnames from Ansible



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








3















This is a follow up to this question.



I have a play that provisions a bunch of EC2 instances. By necessity, the hosts value is localhost (because when it's run there are no hosts), and the play assembles a new host list called ec2hosts, and generates a host ip to hostname map because this is the first and only time that information is made available, and saves it using set_fact. This hosts list is then the subject of a follow-up play. The problem is that I need to use the hostname_map dict created during the provisioning play in the second play, and I can't see how to do this.



Here's the first play:



- hosts: localhost
connection: local
gather_facts: False

tasks:
- name: Provision a set of instances
ec2:
key_name: marcus
instance_type: t2.micro
image: " ami_id "
wait: true
exact_count: " server_count "
count_tag:
Tutorial: " tutorial_name "
instance_tags:
Tutorial: " tutorial_name "
groups: ['SSH', 'Web']
register: ec2

- name: Add all instance public IPs to host group
add_host:
hostname: " item.public_ip "
groups: ec2hosts
loop: " ec2.instances "

- name: Build an IP to hostname map
set_fact:
hostname_map: " combine(item.0.public_ip: (item.1 + '.' + tutorial_domain)) "
loop: " ec2.instances"

- name: Debug hostname_map
debug:
msg: " hostname_map "


At the end of this, hostname_map contains a map like:




"18.184.109.70": "host1.example.com",
"18.196.135.59": "host2.example.com"



From reading the ansible docs on variable scope, it says that variables defined in a play are not available outside that play unless it's being applied to the same set of hosts. That's not possible in this case, so I need to use a var with global scope, and from what I've read, set_fact is the appropriate way to do that. So I created an empty variable in /group_vars/all, so that the variable is accessible to all plays:



hostname_map: 


The next play connects to each newly-created instance (using the host list we created dynamically) and sets its hostname from the inside:



- hosts: ec2hosts
gather_facts: yes
tasks:
- name: Debug hostname_map
debug:
msg: " hostname_map "
- name: Set hostnames
hostname:
name: " hostname_map[ansible_host] "


However, this fails because hostname_map is empty



TASK [Debug hostname_map]
ok: [18.184.109.70] =>
"msg":

ok: [18.196.135.59] =>
"msg":



so I get this error:




fatal: [18.184.109.70]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'18.184.109.70'




Curiously I get the same debug output and error even when I don't define the variable globally.



Other articles I've read all suggest that the values should be enumerated explicitly in vars, but I can't do that because the data is dynamic and unknown until runtime. Similarly, I can't provide it using extra_vars on a command line for the same reason.



How can I make this variable available within the second play? I'd like to avoid clunky solutions like writing a local file out and then reading it back in!



I'm also open to suggestions for doing this a completely different way, where "this" is: create an arbitrary number of EC2 instances and assign them hostnames taken from a static list.










share|improve this question






























    3















    This is a follow up to this question.



    I have a play that provisions a bunch of EC2 instances. By necessity, the hosts value is localhost (because when it's run there are no hosts), and the play assembles a new host list called ec2hosts, and generates a host ip to hostname map because this is the first and only time that information is made available, and saves it using set_fact. This hosts list is then the subject of a follow-up play. The problem is that I need to use the hostname_map dict created during the provisioning play in the second play, and I can't see how to do this.



    Here's the first play:



    - hosts: localhost
    connection: local
    gather_facts: False

    tasks:
    - name: Provision a set of instances
    ec2:
    key_name: marcus
    instance_type: t2.micro
    image: " ami_id "
    wait: true
    exact_count: " server_count "
    count_tag:
    Tutorial: " tutorial_name "
    instance_tags:
    Tutorial: " tutorial_name "
    groups: ['SSH', 'Web']
    register: ec2

    - name: Add all instance public IPs to host group
    add_host:
    hostname: " item.public_ip "
    groups: ec2hosts
    loop: " ec2.instances "

    - name: Build an IP to hostname map
    set_fact:
    hostname_map: " combine(item.0.public_ip: (item.1 + '.' + tutorial_domain)) "
    loop: " ec2.instances"

    - name: Debug hostname_map
    debug:
    msg: " hostname_map "


    At the end of this, hostname_map contains a map like:




    "18.184.109.70": "host1.example.com",
    "18.196.135.59": "host2.example.com"



    From reading the ansible docs on variable scope, it says that variables defined in a play are not available outside that play unless it's being applied to the same set of hosts. That's not possible in this case, so I need to use a var with global scope, and from what I've read, set_fact is the appropriate way to do that. So I created an empty variable in /group_vars/all, so that the variable is accessible to all plays:



    hostname_map: 


    The next play connects to each newly-created instance (using the host list we created dynamically) and sets its hostname from the inside:



    - hosts: ec2hosts
    gather_facts: yes
    tasks:
    - name: Debug hostname_map
    debug:
    msg: " hostname_map "
    - name: Set hostnames
    hostname:
    name: " hostname_map[ansible_host] "


    However, this fails because hostname_map is empty



    TASK [Debug hostname_map]
    ok: [18.184.109.70] =>
    "msg":

    ok: [18.196.135.59] =>
    "msg":



    so I get this error:




    fatal: [18.184.109.70]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'18.184.109.70'




    Curiously I get the same debug output and error even when I don't define the variable globally.



    Other articles I've read all suggest that the values should be enumerated explicitly in vars, but I can't do that because the data is dynamic and unknown until runtime. Similarly, I can't provide it using extra_vars on a command line for the same reason.



    How can I make this variable available within the second play? I'd like to avoid clunky solutions like writing a local file out and then reading it back in!



    I'm also open to suggestions for doing this a completely different way, where "this" is: create an arbitrary number of EC2 instances and assign them hostnames taken from a static list.










    share|improve this question


























      3












      3








      3








      This is a follow up to this question.



      I have a play that provisions a bunch of EC2 instances. By necessity, the hosts value is localhost (because when it's run there are no hosts), and the play assembles a new host list called ec2hosts, and generates a host ip to hostname map because this is the first and only time that information is made available, and saves it using set_fact. This hosts list is then the subject of a follow-up play. The problem is that I need to use the hostname_map dict created during the provisioning play in the second play, and I can't see how to do this.



      Here's the first play:



      - hosts: localhost
      connection: local
      gather_facts: False

      tasks:
      - name: Provision a set of instances
      ec2:
      key_name: marcus
      instance_type: t2.micro
      image: " ami_id "
      wait: true
      exact_count: " server_count "
      count_tag:
      Tutorial: " tutorial_name "
      instance_tags:
      Tutorial: " tutorial_name "
      groups: ['SSH', 'Web']
      register: ec2

      - name: Add all instance public IPs to host group
      add_host:
      hostname: " item.public_ip "
      groups: ec2hosts
      loop: " ec2.instances "

      - name: Build an IP to hostname map
      set_fact:
      hostname_map: " combine(item.0.public_ip: (item.1 + '.' + tutorial_domain)) "
      loop: " ec2.instances"

      - name: Debug hostname_map
      debug:
      msg: " hostname_map "


      At the end of this, hostname_map contains a map like:




      "18.184.109.70": "host1.example.com",
      "18.196.135.59": "host2.example.com"



      From reading the ansible docs on variable scope, it says that variables defined in a play are not available outside that play unless it's being applied to the same set of hosts. That's not possible in this case, so I need to use a var with global scope, and from what I've read, set_fact is the appropriate way to do that. So I created an empty variable in /group_vars/all, so that the variable is accessible to all plays:



      hostname_map: 


      The next play connects to each newly-created instance (using the host list we created dynamically) and sets its hostname from the inside:



      - hosts: ec2hosts
      gather_facts: yes
      tasks:
      - name: Debug hostname_map
      debug:
      msg: " hostname_map "
      - name: Set hostnames
      hostname:
      name: " hostname_map[ansible_host] "


      However, this fails because hostname_map is empty



      TASK [Debug hostname_map]
      ok: [18.184.109.70] =>
      "msg":

      ok: [18.196.135.59] =>
      "msg":



      so I get this error:




      fatal: [18.184.109.70]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'18.184.109.70'




      Curiously I get the same debug output and error even when I don't define the variable globally.



      Other articles I've read all suggest that the values should be enumerated explicitly in vars, but I can't do that because the data is dynamic and unknown until runtime. Similarly, I can't provide it using extra_vars on a command line for the same reason.



      How can I make this variable available within the second play? I'd like to avoid clunky solutions like writing a local file out and then reading it back in!



      I'm also open to suggestions for doing this a completely different way, where "this" is: create an arbitrary number of EC2 instances and assign them hostnames taken from a static list.










      share|improve this question
















      This is a follow up to this question.



      I have a play that provisions a bunch of EC2 instances. By necessity, the hosts value is localhost (because when it's run there are no hosts), and the play assembles a new host list called ec2hosts, and generates a host ip to hostname map because this is the first and only time that information is made available, and saves it using set_fact. This hosts list is then the subject of a follow-up play. The problem is that I need to use the hostname_map dict created during the provisioning play in the second play, and I can't see how to do this.



      Here's the first play:



      - hosts: localhost
      connection: local
      gather_facts: False

      tasks:
      - name: Provision a set of instances
      ec2:
      key_name: marcus
      instance_type: t2.micro
      image: " ami_id "
      wait: true
      exact_count: " server_count "
      count_tag:
      Tutorial: " tutorial_name "
      instance_tags:
      Tutorial: " tutorial_name "
      groups: ['SSH', 'Web']
      register: ec2

      - name: Add all instance public IPs to host group
      add_host:
      hostname: " item.public_ip "
      groups: ec2hosts
      loop: " ec2.instances "

      - name: Build an IP to hostname map
      set_fact:
      hostname_map: " combine(item.0.public_ip: (item.1 + '.' + tutorial_domain)) "
      loop: " ec2.instances"

      - name: Debug hostname_map
      debug:
      msg: " hostname_map "


      At the end of this, hostname_map contains a map like:




      "18.184.109.70": "host1.example.com",
      "18.196.135.59": "host2.example.com"



      From reading the ansible docs on variable scope, it says that variables defined in a play are not available outside that play unless it's being applied to the same set of hosts. That's not possible in this case, so I need to use a var with global scope, and from what I've read, set_fact is the appropriate way to do that. So I created an empty variable in /group_vars/all, so that the variable is accessible to all plays:



      hostname_map: 


      The next play connects to each newly-created instance (using the host list we created dynamically) and sets its hostname from the inside:



      - hosts: ec2hosts
      gather_facts: yes
      tasks:
      - name: Debug hostname_map
      debug:
      msg: " hostname_map "
      - name: Set hostnames
      hostname:
      name: " hostname_map[ansible_host] "


      However, this fails because hostname_map is empty



      TASK [Debug hostname_map]
      ok: [18.184.109.70] =>
      "msg":

      ok: [18.196.135.59] =>
      "msg":



      so I get this error:




      fatal: [18.184.109.70]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'18.184.109.70'




      Curiously I get the same debug output and error even when I don't define the variable globally.



      Other articles I've read all suggest that the values should be enumerated explicitly in vars, but I can't do that because the data is dynamic and unknown until runtime. Similarly, I can't provide it using extra_vars on a command line for the same reason.



      How can I make this variable available within the second play? I'd like to avoid clunky solutions like writing a local file out and then reading it back in!



      I'm also open to suggestions for doing this a completely different way, where "this" is: create an arbitrary number of EC2 instances and assign them hostnames taken from a static list.







      amazon-ec2 ansible






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 8 at 14:56







      Synchro

















      asked Apr 8 at 14:51









      SynchroSynchro

      1,83541829




      1,83541829




















          1 Answer
          1






          active

          oldest

          votes


















          4














          A value you set with set_fact will be available between different plays. Keep in mind that set_fact are set for a specific host. Your first play is run against localhost so the fact is part of the localhosts variables. So it the following play you should be able to access it with a task like this.



          - debug:
          var: hostvars['localhost']['hostmap']





          share|improve this answer























          • Spot on, thank you.

            – Synchro
            Apr 8 at 23:07











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "2"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f962040%2fsharing-ansible-variable-between-plays%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          A value you set with set_fact will be available between different plays. Keep in mind that set_fact are set for a specific host. Your first play is run against localhost so the fact is part of the localhosts variables. So it the following play you should be able to access it with a task like this.



          - debug:
          var: hostvars['localhost']['hostmap']





          share|improve this answer























          • Spot on, thank you.

            – Synchro
            Apr 8 at 23:07















          4














          A value you set with set_fact will be available between different plays. Keep in mind that set_fact are set for a specific host. Your first play is run against localhost so the fact is part of the localhosts variables. So it the following play you should be able to access it with a task like this.



          - debug:
          var: hostvars['localhost']['hostmap']





          share|improve this answer























          • Spot on, thank you.

            – Synchro
            Apr 8 at 23:07













          4












          4








          4







          A value you set with set_fact will be available between different plays. Keep in mind that set_fact are set for a specific host. Your first play is run against localhost so the fact is part of the localhosts variables. So it the following play you should be able to access it with a task like this.



          - debug:
          var: hostvars['localhost']['hostmap']





          share|improve this answer













          A value you set with set_fact will be available between different plays. Keep in mind that set_fact are set for a specific host. Your first play is run against localhost so the fact is part of the localhosts variables. So it the following play you should be able to access it with a task like this.



          - debug:
          var: hostvars['localhost']['hostmap']






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 8 at 17:33









          ZoredacheZoredache

          112k30231379




          112k30231379












          • Spot on, thank you.

            – Synchro
            Apr 8 at 23:07

















          • Spot on, thank you.

            – Synchro
            Apr 8 at 23:07
















          Spot on, thank you.

          – Synchro
          Apr 8 at 23:07





          Spot on, thank you.

          – Synchro
          Apr 8 at 23:07

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Server Fault!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f962040%2fsharing-ansible-variable-between-plays%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          rnmiX8JTza0NwkgvHnjmE1Q gR9spcG,af NBsXNgQEnGEQgalCPjL4NeFGl4kzbA44
          7 qaaD2YFBhE EpumMqakKldD7rl dJ4G

          Popular posts from this blog

          RemoteApp sporadic failureWindows 2008 RemoteAPP client disconnects within a matter of minutesWhat is the minimum version of RDP supported by Server 2012 RDS?How to configure a Remoteapp server to increase stabilityMicrosoft RemoteApp Active SessionRDWeb TS connection broken for some users post RemoteApp certificate changeRemote Desktop Licensing, RemoteAPPRDS 2012 R2 some users are not able to logon after changed date and time on Connection BrokersWhat happens during Remote Desktop logon, and is there any logging?After installing RDS on WinServer 2016 I still can only connect with two users?RD Connection via RDGW to Session host is not connecting

          Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

          Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020