LoginSignup
1
0

More than 3 years have passed since last update.

AWSのCloudFormationのテンプレートを作成中に依存循環のエラーが発生した。

Posted at

cloudFormationを使っていたところ、依存循環のエラーが発生し少しハマってしまった。
AWS初学者です。エンジニアとして一年目なので、そこを考慮して見ていただけると幸いです。間違っている点などありましたら、教えてください。。

環境

Amzon Linux2

エラーの内容

cloudformationのテンプレート作成中に以下のエラーが発生。調べると、依存循環のエラーとのことらしい。

[cfn-lint] E3004: Circular Dependencies for resource Ec2InstanceServer.  Circular dependency with [WpLaunchTemplate, Ec2InstanceServer]

以下、エラーが出たコード部分です。

---省略---
Parameters:
  DBPassword:
    NoEcho: true
    Description: The database admin account password
    Type: String
    MinLength: 8
    MaxLength: 41
    AllowedPattern: '[a-zA-Z0-9]*'
    ConstraintDescription: must contain only alphanumeric characters.

---省略---

Resources:
 WpLaunchTemplate:
  Type: AWS::EC2::LaunchTemplate
  Properties:
   LaunchTemplateName: wp-launch-template
   LaunchTemplateData:
    UserData:
      Fn::Base64: !Sub
        - |
          #!/bin/bash
---省略---
          echo 'grant all on wpdb.* to wpadmin@${Ec2Ipaddress} identified by '${DBPassword}'' | mysql --defaults-extra-file=/etc/my.cnf.d/client.cnf
        - {
           Ec2Ipaddress: !GetAtt Ec2InstanceServer.PrivateIp,
          }

---省略---

EC2のUserDataの中で自リソースを!GetAttで参照していたことがエラーの原因とのこと。
CloudFormationでは、組込関数(!Refや!GetAttなど)を使用すると、依存関係が自動的に作られる。
Aリソース内に!RefでBリソースを参照した場合、リソースが作成される順番は
 Bリソース → Aリソース

依存循環のエラーになる場合
Aリソース内に!RefでBリソースを参照しかつ、Bリソース内でも!Refなどの組込関数でAリソースを参照した時。
 Bリソース ⇄ Aリソース
上のような状態になり、どちらから作成していいのか判断できなくなる。

解決

EC2のパブリックIpアドレスをシェルスクリプト内で使用したかっただけなので、以下のようにコマンドを修正し、!GetAttを削除。
grant all on wpdb.* to 'wpadmin'@'hostname -i' identified by '${DBPassword}';
元々、シェルスクリプトやコマンドについての知識不足で、この書き方に気づけなかった。

ちなみに複数のIPアドレスが振られている場合は以下のようにした。

// eth0
$ hostname -I | cut -f1 -d' '
// eth1
$ hostname -I | cut -f2 -d' '

各コマンドについて

①cutコマンドについて
cut -f 項目数 -d 区切り文字 ファイル名
ex)
cut -f 2 -d ":" sample.txt
ファイルsample.txtを「:」の文字で区切り、その2項目目を表示するコマンド

②hostnameコマンドについて
hostname -i
ホストのIPアドレスを表示するコマンド

参考

組込関数について
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
循環依存について
https://note.com/amakata/n/n914e5b87fbcd
cut・hosnameのコマンドについて
https://moomindani.wordpress.com/2014/09/17/linux-command-ip-address/

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0