64

AmazonLinuxAMIに基づくAMIを実行しているEC2インスタンスがあります。このようなすべてのAMIと同様に、すべてのインスタンスに渡されたユーザーデータに基づいて起動スクリプトを実行するためのcloud-initシステムをサポートします。この特定のケースでは、私のユーザーデータ入力は、他のいくつかの起動スクリプトをソースするインクルードファイルです。

#include
http://s3.amazonaws.com/path/to/script/1
http://s3.amazonaws.com/path/to/script/2

インスタンスを初めて起動すると、cloud-init起動スクリプトが正しく実行されます。ただし、インスタンスのソフトリブートを実行すると(たとえば、を実行して) 、2回目に起動スクリプトを実行せずsudo shutdown -r nowにインスタンスが再起動します。システムログを見ると、次のことがわかります。

Running cloud-init user-scripts
user-scripts already ran once-per-instance
[  OK  ]

これは私が望んでいることではありません-インスタンスの存続期間ごとに1回だけ実行される起動スクリプトを持つユーティリティを見ることができますが、私の場合、通常の起動スクリプトのように、インスタンスが起動するたびに実行する必要があります。

rc.local考えられる解決策の1つは、最初に実行した後にスクリプトを手動で挿入することです。ただし、cloud-init環境とrc.d環境は微妙に異なり、最初の起動時とその後のすべての起動時にスクリプトを個別にデバッグする必要があるため、これは厄介なようです。

cloud-initに常にスクリプトを実行するように指示する方法を知っている人はいますか?これは確かに、cloud-initの設計者が検討したであろうことのように聞こえます。

4

8 に答える 8

64

11.10、12.04以降では、「scripts-user」を「always」で実行することでこれを実現できます。/etc/cloud/cloud.cfgには、次のようなものが表示されます。

cloud_final_modules:
 - rightscale_userdata
 - scripts-per-once
 - scripts-per-boot
 - scripts-per-instance
 - scripts-user
 - keys-to-console
 - phone-home
 - final-message

これは起動後に変更できます。または、このスタンザをオーバーライドするcloud-configデータをuser-dataを介して挿入できます。つまり、ユーザーデータで提供できるのは次のとおりです。

#cloud-config
cloud_final_modules:
 - rightscale_userdata
 - scripts-per-once
 - scripts-per-boot
 - scripts-per-instance
 - [scripts-user, always]
 - keys-to-console
 - phone-home
 - final-message

説明で行ったように、これを「#include」することもできます。残念ながら、現時点では、「cloud_final_modules」を変更することはできず、オーバーライドするだけです。いつか設定セクションを変更する機能を追加したいと思っています。

これについては、 https://github.com/canonical/cloud-init/tree/master/doc/examplesのcloud-configドキュメントにもう少し詳しい情報があり ます。

または、ファイルを/ var / lib / cloud / scripts / per-bootに配置すると、「scripts-per-boot」パスで実行されます。

于 2012-05-04T19:31:06.583 に答える
21

/etc/init.d/cloud-init-user-scripts、次の行を編集します。

/usr/bin/cloud-init-run-module once-per-instance user-scripts execute run-parts ${SCRIPT_DIR} >/dev/null && success || failure

 /usr/bin/cloud-init-run-module always user-scripts execute run-parts ${SCRIPT_DIR} >/dev/null && success || failure

幸運を !

于 2011-12-04T18:40:27.600 に答える
12

cloud-initはこれをネイティブにサポートするようになりました。ドキュメント( http://cloudinit.readthedocs.io/en/latest/topics/examples.html#run-commands-on-first-boot)のruncmdとbootcmdのコマンドの説明を参照してください。

"runcmd":

#cloud-config

# run commands
# default: none
# runcmd contains a list of either lists or a string
# each item will be executed in order at rc.local like level with
# output to the console
# - runcmd only runs during the first boot
# - if the item is a list, the items will be properly executed as if
#   passed to execve(3) (with the first arg as the command).
# - if the item is a string, it will be simply written to the file and
#   will be interpreted by 'sh'
#
# Note, that the list has to be proper yaml, so you have to quote
# any characters yaml would eat (':' can be problematic)
runcmd:
 - [ ls, -l, / ]
 - [ sh, -xc, "echo $(date) ': hello world!'" ]
 - [ sh, -c, echo "=========hello world'=========" ]
 - ls -l /root
 - [ wget, "http://slashdot.org", -O, /tmp/index.html ]

"bootcmd":

#cloud-config

# boot commands
# default: none
# this is very similar to runcmd, but commands run very early
# in the boot process, only slightly after a 'boothook' would run.
# bootcmd should really only be used for things that could not be
# done later in the boot process.  bootcmd is very much like
# boothook, but possibly with more friendly.
# - bootcmd will run on every boot
# - the INSTANCE_ID variable will be set to the current instance id.
# - you can use 'cloud-init-per' command to help only run once
bootcmd:
 - echo 192.168.1.130 us.archive.ubuntu.com >> /etc/hosts
 - [ cloud-init-per, once, mymkfs, mkfs, /dev/vdb ]

また、bootcmdの「cloud-init-per」コマンドの例にも注意してください。それの助けから:

Usage: cloud-init-per frequency name cmd [ arg1 [ arg2 [ ... ] ]
   run cmd with arguments provided.

   This utility can make it easier to use boothooks or bootcmd
   on a per "once" or "always" basis.

   If frequency is:
      * once: run only once (do not re-run for new instance-id)
      * instance: run only the first boot for a given instance-id
      * always: run every boot
于 2017-07-06T10:03:36.323 に答える
8

1つの可能性は、多少ハックですが、cloud-initがuser-scriptがすでに実行されているかどうかを判断するために使用するロックファイルを削除することです。私の場合(Amazon Linux AMI)、このロックファイルはにあり、/var/lib/cloud/sem/名前が付けられuser-scripts.i-7f3f1d11ています(最後のハッシュ部分は起動ごとに変更されます)。したがって、インクルードファイルの最後に追加された次のユーザーデータスクリプトがトリックを実行します。

#!/bin/sh
rm /var/lib/cloud/sem/user-scripts.*

これが他の何かに悪影響を与えるかどうかはわかりませんが、私の実験ではうまくいきました。

于 2011-06-25T19:55:51.033 に答える
3

bashスクリプトの上にある以下のスクリプトを使用してください。

例:ここでmhelloworldをファイルに出力します

ユーザーデータに追加する前にインスタンスを停止します

脚本

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
/bin/echo "Hello World." >> /var/tmp/sdksdfjsdlf
--//
于 2018-12-20T10:13:44.123 に答える
2

私はこの問題にほぼ2日間苦労し、見つけたすべての解決策を試し、最後にいくつかのアプローチを組み合わせて、次のことを思いつきました。

MyResource:
  Type: AWS::EC2::Instance
  Metadata:
    AWS::CloudFormation::Init:
      configSets:
        setup_process:
          - "prepare"
          - "run_for_instance"
      prepare:
        commands:
          01_apt_update:
            command: "apt-get update"
          02_clone_project:
            command: "mkdir -p /replication && rm -rf /replication/* && git clone https://github.com/awslabs/dynamodb-cross-region-library.git /replication/dynamodb-cross-region-library/"
          03_build_project:
            command: "mvn install -DskipTests=true"
            cwd: "/replication/dynamodb-cross-region-library"
          04_prepare_for_apac:
            command: "mkdir -p /replication/replication-west && rm -rf /replication/replication-west/* && cp /replication/dynamodb-cross-region-library/target/dynamodb-cross-region-replication-1.2.1.jar /replication/replication-west/replication-runner.jar"
      run_for_instance:
        commands:
          01_run:
            command: !Sub "java -jar replication-runner.jar --sourceRegion us-east-1 --sourceTable ${TableName} --destinationRegion ap-southeast-1 --destinationTable ${TableName} --taskName -us-ap >/dev/null 2>&1 &"
            cwd: "/replication/replication-west"
  Properties:
    UserData:
      Fn::Base64:
        !Sub |
          #cloud-config
          cloud_final_modules:
           - [scripts-user, always]
          runcmd:
           - /usr/local/bin/cfn-init -v -c setup_process --stack ${AWS::StackName} --resource MyResource --region ${AWS::Region}
           - /usr/local/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource MyResource --region ${AWS::Region}

これは、DynamoDbクロスリージョンレプリケーションプロセスのセットアップです。

于 2018-01-09T14:22:33.347 に答える
2

誰かがCDKでこれを実行したい場合は、Pythonの例を次に示します。

Windowsの場合、ユーザーデータには特別なpersistタグがありますが、Linuxの場合、最初にcloud-initを設定するためにMultiPartユーザーデータを使用する必要があります。このLinuxの例は、cloud-configref blogを参照)パーツタイプで機能しましたが、テストできなかった(bootcmdも参照)呼び出しcloud-boothookが必要です(例:) 。cloud-init-percloud-init-pre always

Linuxの例:

    # Create some userdata commands
    instance_userdata = ec2.UserData.for_linux()
    instance_userdata.add_commands("apt update")
    # ...
    # Now create the first part to make cloud-init run it always
    cinit_conf = ec2.UserData.for_linux();
    cinit_conf .add_commands('#cloud-config');
    cinit_conf .add_commands('cloud_final_modules:');
    cinit_conf .add_commands('- [scripts-user, always]');
    multipart_ud = ec2.MultipartUserData()
    #### Setup to run every time instance starts
    multipart_ud.add_part(ec2.MultipartBody.from_user_data(cinit_conf , content_type='text/cloud-config'))
    #### Add the commands desired to run every time
    multipart_ud.add_part(ec2.MultipartBody.from_user_data(instance_userdata));

    ec2.Instance(
        self, "myec2",
        userdata=multipart_ud,
        #other required config...
    )

Windowsの例:

    instance_userdata = ec2.UserData.for_windows()
    # Bootstrap
    instance_userdata.add_commands("Write-Output 'Run some commands'")
    # ...
    # Making all the commands persistent - ie: running on each instance start
    data_script = instance_userdata.render()
    data_script += "<persist>true</persist>"
    ud = ec2.UserData.custom(data_script)
    ec2.Instance(
        self, "myWinec2",
        userdata=ud,
        #other required config...
    )
于 2021-11-03T06:25:12.453 に答える
1

もう1つのアプローチは#cloud-boothook、ユーザーデータスクリプトで使用することです。ドキュメントから:

クラウドブートフック

  • #cloud-boothookまたはContent-Type:text/cloud-boothookで始まります。
  • このコンテンツはブートフックデータです。/ var / lib / cloudの下のファイルに保存され、すぐに実行されます。
  • これは、利用可能な最も初期の「フック」です。1回だけ実行するためのメカニズムはありません。ブートフックはこれ自体を処理する必要があります。これは、環境変数INSTANCE_IDのインスタンスIDで提供されます。この変数を使用して、インスタンスごとに1回のブートフックデータのセットを提供します。
于 2019-07-25T21:19:03.730 に答える