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

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







          Popular posts from this blog

          Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

          Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

          What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company